簡體   English   中英

作為數組數組的地圖對象的javascript查找值

[英]javascript lookup value of a map object which is array of array

我有一個 JS map對象(這里是 JS 的新手),它是一個數組數組,如下所示:

scores=[["key_1",true],["key_2",false],["key_3",false]....["key_n",true]]

我可以像這樣訪問控制台上的值:

scores[0] //outputs ["key_1",true]
scores[0][0] //outputs "key_"
//..and so on.

但是,我如何對對象數組中的特定鍵進行(快速)查找,例如:

scores[["key_3"]] //obviously wont work
//expected output: false

你可以簡單地find鑰匙。

 const scores=[ ["key_1",true], ["key_2",false], ["key_3",false], ["key_4",true] ]; var score = scores.find(score => score[0]==="key_3") console.log(score[0]+" is "+score[1])

返回:

key_3 is false

您還可以將數組數組轉換為Map對象。

輕松訪問鍵值對,同時它仍然是可迭代的。

 const scores=[ ["key_1",true], ["key_2",false],["key_3",false], ["key_4",true] ] var scoreMap = new Map(); scores.forEach(score => scoreMap.set(score[0], score[1])) console.log("key_4 is "+ scoreMap.get("key_4")) console.log([...scoreMap.keys()])

使用Object.fromEntries()將數組轉換為對象。

使用Object.entries()變回數組。

 var scores = [ ["key_1", true], ["key_2", false], ["key_3", false], ["key_4", true] ]; scores = Object.fromEntries(scores); console.log(scores.key_3);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM