Kracki
Kracki

Reputation: 63

Getting particular object from nested complex object

I have a below json, want to get object whose id = 111 , depth may vary depending upon the json.

object = [ 
           { 
             id= 1,
             name : 'a',
             childNodes : [ {
                            id=11,
                            name:'aa',
                            childNodes:[{
                                         id: 111,
                                         name:'aaaa',
                                         childNodes:[]
                                        }]
                       }]

           }]

required output { id: 111, name:'aaaa', childNodes:[] }

Looking for fastest algorithm or method. Data would be really huge of more then 35000 nodes and depth upto 20.

Any help would be appreciated.

Upvotes: 0

Views: 65

Answers (2)

trincot
trincot

Reputation: 350831

Here is a recursive function using some:

function findNested(arr, id) {
    var res;
    return arr.some(o => res = Object(o).id === id ? o 
                             : findNested(o.childNodes, id) ) && res;
}

var object = [{ 
    id: 1,
    name : 'a',
    childNodes : [ {
        id: 11,
        name:'aa',
        childNodes:[{
            id: 111,
            name:'aaaa',
            childNodes:[]
        }]
    }]
}];

console.log(findNested(object, 111));
console.log(findNested(object, 9));

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can create recursive function for this using for...in loop.

var object = [{"id":1,"name":"a","childNodes":[{"id":11,"name":"aa","childNodes":[{"id":111,"name":"aaaa","childNodes":[]}]}]},{"id":2,"name":"a","childNodes":[{"id":22,"name":"aa","childNodes":[{"id":123,"name":"aaaa","childNodes":[]}]}]}]  

function findById(data, id) {
  for(var i in data) {
    var result;
    if(data.id == id) return data
    if(typeof data[i] == 'object' && (result = findById(data[i], id))) return result
  }
}

console.log(findById(object, 111))
console.log(findById(object, 22))

Upvotes: 1

Related Questions