亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 lodash 訪問對象

使用 lodash 訪問對象

神不在的星期二 2023-05-11 10:26:55
我正在嘗試使用 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 = inputlet found = indexOf(areaCode, ["area_code", code]);const city = areaCode[found].city但是發現是-1,我做錯了什么?
查看完整描述

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


查看完整回答
反對 回復 2023-05-11
?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

我相信_.findIndex()

let?found?=?findIndex(areaCode,?["area_code",?code]);


查看完整回答
反對 回復 2023-05-11
?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

根據文檔_.indexOf將執行SameValueZero比較來定位索引。簡而言之,因為indexOf(data, item)它會嘗試使用===to compareitemdata.

相反,您可以使用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>



查看完整回答
反對 回復 2023-05-11
  • 3 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號