#javascript #lodash
#javascript #lodash
Вопрос:
Я пытаюсь использовать indexOf, чтобы найти ключ в массиве, который выглядит следующим образом
const areaCode = [
{
"area_code": 656,
"city": "city1"
},
{
"area_code": 220,
"city": "city2"
},
{
"area_code": 221,
"city": "city3"
}]
export default areaCode
Затем я пытаюсь получить название города на основе номера area_code
const code = input
let found = indexOf(areaCode, ["area_code", code]);
const city = areaCode[found].city
Но найденное равно -1, что я делаю не так?
Комментарии:
1. Какова ценность
code
?2. это допустимый area_code! например, 656 или 221 в приведенном выше примере
3. На самом деле,
indexOf
не используетсяiteratee
для поиска — он выполняет сравнение SameValueZero. Какая-либо конкретная причина использовать его вместо justfind
?
Ответ №1:
Вы должны использовать функцию Lodash _.find .
Это было бы так:
const areaCode = [
{
"area_code": 656,
"city": "city1"
},
{
"area_code": 220,
"city": "city2"
},
{
"area_code": 221,
"city": "city3"
}]
const code = input;
const found = _.find(areaCode, function(a){ return a.area_code == code });
console.log(found.city)
найденная константа будет содержать соответствующую область.
Ответ №2:
Я считаю _.findIndex()
, что это то, что вам нужно: https://lodash.com/docs/4.17.15#findIndex
let found = findIndex(areaCode, ["area_code", code]);
Вот демонстрация https://jsbin.com/ruqayunini/edit?html ,js, консоль, вывод
Ответ №3:
Согласно документации _.indexOf
, будет выполнено сравнение SameValueZero для определения индекса. Короче говоря, для indexOf(data, item)
этого он будет пытаться использовать ===
для сравнения item
с каждой записью data
.
Вместо этого вы можете использовать _.findIndex
which принимает обычное сокращение для _.matchesProperty
that будет принято _.iteratee
:
const { findIndex } = _;
const areaCode = [
{
"area_code": 656,
"city": "city1"
},
{
"area_code": 220,
"city": "city2"
},
{
"area_code": 221,
"city": "city3"
}]
const code = 220;
let found = findIndex(areaCode, ["area_code", code]);
console.log("index:", found);
const city = areaCode[found].city
console.log("city:", city);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
Хотя, учитывая ваше использование, вы, вероятно, захотите _.find
const { find } = _;
const areaCode = [
{
"area_code": 656,
"city": "city1"
},
{
"area_code": 220,
"city": "city2"
},
{
"area_code": 221,
"city": "city3"
}]
const code = 220;
let found = find(areaCode, ["area_code", code]);
console.log("index:", found);
const city = found.city
console.log("city:", city);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>