3 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
你應(yīng)該使用 Lodash _.find 函數(shù)。
它會(huì)是這樣的:
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 將保存匹配區(qū)域。
https://lodash.com/docs/4.17.15#find

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
我相信_.findIndex()
let?found?=?findIndex(areaCode,?["area_code",?code]);

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
根據(jù)文檔_.indexOf
將執(zhí)行SameValueZero比較來定位索引。簡而言之,因?yàn)?code>indexOf(data, item)它會(huì)嘗試使用===
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>
添加回答
舉報(bào)