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: [] } ] }
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.
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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With