I’m looking for a couple of different ways to access the data below, using ES6 and/or lodash.
What I’m trying to do is to return the parent object, where device_id matches.
i.e, for each item in entities, if in any of the nested objects, the device_id field = abc, return the whole array item
const entities = [
{
"<unknown key>": {
"entity_id": "something",
"device_id": "abc"
},
"<unknown key>": {
"entity_id": "else",
"device_id": "abc"
},
},
{
"<unknown key>": {
"entity_id": "hello",
"device_id": "xyz"
},
"<unknown key>": {
"entity_id": "world",
"device_id": "xyz"
}
}
]
2
Answers
Use
Array#filter
in conjunction withArray#some
to get all matches. If only one match is desired, replacefilter
withfind
.Here’s some generic code:
Applied to your object like this:
this will return an array of the matching object and all intermediate objects.
Replace
concat([v])
withconcat([k])
if you want a list of keys instead.