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.
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 . 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
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.
You can also use filter
, if there are multiple existence of id qwsa221
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.