[英]How to access an array of objects which is a key-value pair
i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element. 我想在不使用数组索引的情况下访问id'qwsa221',但只能访问并输出所有数组元素,而不是特定元素。
i have tried using filter but couldnt figure out how to use it properly. 我曾尝试使用过滤器,但无法弄清楚如何正确使用它。
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys()
to get all the keys of the object and check the values in the array elements using . 使用
Object.keys()
获取对象的所有键,并使用来检查数组元素中的值。 notation 符号
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) }) })
you can do it like this, using find
您可以使用
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" ) )
here's a corrected version of your filter : 这是您的过滤器的更正版本:
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])
You can use Object.Keys
method to iterate through all of the keys present. 您可以使用
Object.Keys
方法来迭代存在的所有键。
You can also use filter
, if there are multiple existence of id qwsa221
如果存在多个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.