![](/img/trans.png)
[英]How to get a value of array of objects (pair key-value) in javascript?
[英]How to access an array of objects which is a key-value pair
我想在不使用數組索引的情況下訪問id'qwsa221',但只能訪問並輸出所有數組元素,而不是特定元素。
我曾嘗試使用過濾器,但無法弄清楚如何正確使用它。
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
使用Object.keys()
獲取對象的所有鍵,並使用來檢查數組元素中的值。 符號
let lists = { def453ed: [{ id: "qwsa221", name: "Mind" }, { id: "jwkh245", name: "Space" } ] }; Object.keys(lists).forEach(function(e) { lists[e].forEach(function(x) { if (x.id == 'qwsa221') console.log(x) }) })
您可以使用find
這樣做
let lists = { def453ed: [ { id: "qwsa221", name: "Mind" }, { id: "jwkh245", name: "Space" } ] }; console.log( lists.def453ed // first get the array .find( // find return the first entry where the callback returns true el => el.id === "qwsa221" ) )
這是您的過濾器的更正版本:
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]}; // what you've done const badResult = lists.def453ed.filter(id => id === "qwsa221"); /* here id is the whole object { id: "qwsa221", name: "Mind" } */ console.log(badResult) // the correct way const goodResult = lists.def453ed.filter(el => el.id === "qwsa221"); console.log(goodResult) // filter returns an array so you need to actually get the first entry console.log(goodResult[0])
您可以使用Object.Keys
方法來迭代存在的所有鍵。
如果存在多個id qwsa221
,也可以使用filter
。
let lists = { def453ed: [ { id: "qwsa221", name: "Mind" }, { id: "jwkh245", name: "Space" } ] }; let l = Object.keys(lists) .map(d => lists[d] .find(el => el.id === "qwsa221")) console.log(l)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.