Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through Nested JavaScript Objects [duplicate]

I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I can't wrap my head around how to iterate down through the tree to return the appropriate object. Any help or suggestions would be greatly appreciated.

var cars = {   label: 'Autos',   subs: [     {       label: 'SUVs',       subs: []     },     {       label: 'Trucks',       subs: [         {           label: '2 Wheel Drive',           subs: []         },         {           label: '4 Wheel Drive',           subs: [             {               label: 'Ford',               subs: []             },             {               label: 'Chevrolet',               subs: []             }           ]         }       ]     },     {       label: 'Sedan',       subs: []     }   ] } 
like image 532
NewToThis Avatar asked Nov 10 '11 19:11

NewToThis


People also ask

How do I iterate over a nested object in JavaScript?

You can create a function to loop through nested objects. That function automatically will check for nested objects and go through that objects. The for...in loop and Object. keys() method return keys/properties of the object.

How do you loop through a nested array?

After creating a JavaScript nested array, you can use the “push()” and “splice()” method for adding elements, “for loop” and “forEach()” method to iterate over the elements of the inner arrays, “flat()” method for reducing the dimensionality, and “pop()” method to delete sub-arrays or their elements from the nested ...

Can you loop through objects JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.


1 Answers

In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys(), recursively:

const iterate = (obj) => {     Object.keys(obj).forEach(key => {      console.log(`key: ${key}, value: ${obj[key]}`)      if (typeof obj[key] === 'object' && obj[key] !== null) {             iterate(obj[key])         }     }) } 

REPL example.

like image 85
Menelaos Kotsollaris Avatar answered Sep 26 '22 02:09

Menelaos Kotsollaris