Home >Web Front-end >JS Tutorial >How to Recursively Iterate Through Nested JavaScript Objects?
Problem:
How to recursively iterate through a deeply nested JavaScript object to retrieve a specific object based on a given identifier (e.g., "label" property)?
Solution:
To deeply iterate through a nested object using recursion:
<code class="js">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]); } }); }; console.log(iterate({ ...cars }));</code>
For a non-recursive approach:
<code class="js">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]); } }); } }; console.log(iterate({ ...cars }));</code>
In both approaches, the key and value of each nested object are logged to the console.
The above is the detailed content of How to Recursively Iterate Through Nested JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!