Home > Web Front-end > JS Tutorial > How to Recursively Iterate Through Nested JavaScript Objects?

How to Recursively Iterate Through Nested JavaScript Objects?

DDD
Release: 2024-11-02 02:25:31
Original
530 people have browsed it

How to Recursively Iterate Through Nested JavaScript Objects?

Iterating through Nested JavaScript Objects [Duplicate]

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:

Original Answer with Recursion

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>
Copy after login

2023 Update: Non-Recursive Approach

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template