3 回答
TA贡献1779条经验 获得超6个赞
你应该使用 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)
const found 将保存匹配区域。
https://lodash.com/docs/4.17.15#find
TA贡献1829条经验 获得超7个赞
根据文档_.indexOf
将执行SameValueZero比较来定位索引。简而言之,因为indexOf(data, item)
它会尝试使用===
to compareitem
与data
.
相反,您可以使用which accepts将被接受的_.findIndex
常用简写:_.matchesProperty
_.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>
添加回答
举报