Home > Web Front-end > JS Tutorial > body text

How Can You Iterate Through Nested JavaScript Objects?

Mary-Kate Olsen
Release: 2024-11-03 05:24:31
Original
661 people have browsed it

How Can You Iterate Through Nested JavaScript Objects?

Iterating through Nested JavaScript Objects

Iterating through nested JavaScript objects can be challenging, particularly when you need to retrieve a specific object identified by a specific property value. Consider the below example:

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: []
    }
  ]
};
Copy after login

Recursive Iterative Approach:

To traverse deeply through the object hierarchy, you can utilize a recursive approach:

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])
        }
    })
}
Copy after login

This function recursively iterates through the object, printing the key-value pairs at each level. If an encountered property holds another object, the function calls itself with that object as the argument.

Non-Recursive Iterative Approach:

An alternative non-recursive approach involves using a stack data structure:

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]);
            }
        });
    }
};
Copy after login

This function iterates through the object hierarchy by utilizing a stack. It pops the last element from the stack and iterates through its properties. If a property holds an object, it pushes that object onto the stack for further iteration.

The above is the detailed content of How Can You 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template