"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Find a Specific Object in Nested JavaScript Objects?

How to Efficiently Find a Specific Object in Nested JavaScript Objects?

Published on 2024-11-09
Browse:165

How to Efficiently Find a Specific Object in Nested JavaScript Objects?

Iterating through Nested JavaScript Objects

Iterating through nested JavaScript objects can be challenging, especially when you need to retrieve specific objects based on a property value. Let's consider the following 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: []
    }
  ]
};

If we want to retrieve the object for the "Ford" brand, we can use a recursive approach:

const iterate = (obj, identifier) => {
  for (let key in obj) {
    if (obj[key]['label'] === identifier) {
      return obj[key];
    }
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      const result = iterate(obj[key], identifier);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

const fordObject = iterate(cars, 'Ford');

In this example, the iterate function takes two parameters: the object to search and the identifier string. It iterates through the properties of the object, checking if the label property matches the identifier. If not, it checks if the property is another object and continues the iteration. If no matching object is found, it returns null.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3