To traverse a nested JavaScript object and locate an object with a specific label, follow these steps:
To recursively iterate through the nested object:
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]) } }) } iterate(obj); // obj is the main object to be traversed
For a non-recursive approach:
const iterate = (obj) => { const stack = [obj]; while (stack?.length > 0) { const currentObj = stack.pop(); Object.keys(currentObj).forEach(key => { console.log(`key: ${key}, value: ${currentObj[key]}`); if (typeof currentObj[key] === 'object' && currentObj[key] !== null) { stack.push(currentObj[key]); } }); } };
Consider the following nested object:
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: [] } ] };
To retrieve the object with the label "4 Wheel Drive" using the recursive approach, call:
iterate(cars);
To retrieve the same object using the non-recursive approach, call:
iterate(cars);
This will log all the key-value pairs in the nested object, including the desired object.
The above is the detailed content of How to Find a Specific Object within a Nested JavaScript Object by Label?. For more information, please follow other related articles on the PHP Chinese website!