skip to Main Content

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


  1. Use Array#filter in conjunction with Array#some to get all matches. If only one match is desired, replace filter with find.

    let search = 'abc';
    const entities=[{"<unknown key>":{entity_id:"something",device_id:"abc"},"<unknown key2>":{entity_id:"else",device_id:"abc"}},{"<unknown key>":{entity_id:"hello",device_id:"xyz"},"<unknown key2>":{entity_id:"world",device_id:"xyz"}}];
    const res  = entities.filter(o => Object.values(o)
                    .some(x => x.device_id === search));
    console.log(res);
    Login or Signup to reply.
  2. Here’s some generic code:

    function findPath(obj, fn, path = []) {
        if (typeof obj !== 'object')
            return
    
        if (fn(obj))
            return path
        
        for (let [k, v] of Object.entries(obj)) {
            let p = findPath(v, fn, path.concat([v]))
            if (p)
                return p
        }
    }
    

    Applied to your object like this:

    findPath(entities, x => x.device_id === 'xyz')
    

    this will return an array of the matching object and all intermediate objects.

    Replace concat([v]) with concat([k]) if you want a list of keys instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search