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/[email protected]/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/[email protected]/lodash.min.js"></script>
添加回答
舉報