Find all values by specific key in a deep nested object | Javascript

  • A+
Category:Languages

How would I Find all values by specific key in a deep nested object?

For example, if I have an object like this:

const myObj = {   id: 1,   children: [     {       id: 2,       children: [         {           id: 3         }       ]     },     {       id: 4,       children: [         {           id: 5,           children: [             {               id: 6,               children: [                 {                   id: 7,                 }               ]             }           ]         }       ]     },   ] } 

How would I get an array of all values throughout all nests of this obj by the key of id.

Note: children is a consistent name, and id's wont exist outside of a children object.

So from the obj, I would like to produce an array like this:

const idArray = [1, 2, 3, 4, 5, 6, 7] 

Thanks in advance!

 


You could make a recursive function like this:

idArray = []  function func(obj) {   idArray.push(obj.id)   if (!obj.children) {     return   }    obj.children.forEach(child => func(child)) } 

Snippet for your sample:

const myObj = {   id: 1,   children: [{       id: 2,       children: [{         id: 3       }]     },     {       id: 4,       children: [{         id: 5,         children: [{           id: 6,           children: [{             id: 7,           }]         }]       }]     },   ] }  idArray = []  function func(obj) {   idArray.push(obj.id)   if (!obj.children) {     return   }    obj.children.forEach(child => func(child)) }  func(myObj) console.log(idArray)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: