"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 Find Nested Objects by Key in JavaScript?

How to Find Nested Objects by Key in JavaScript?

Posted on 2025-02-06
Browse:537

How to Find Nested Objects by Key in JavaScript?

Finding Nested Objects by Key

Navigating deeply nested arrays and objects to find a specific value can be a challenging task. Consider the scenario where you have a complex data structure like the one provided. To locate an object with a specific 'id' property nested several levels deep, you can utilize recursion.

Recursive Solution

The provided function, 'getObject', takes an object as input and iterates over its properties. If a property is an array, the function recursively searches each element. Otherwise, the function checks if the property is the desired 'id' and returns the object if a match is found.

function getObject(theObject) {
    var result = null;
    if (theObject instanceof Array) {
        for (var i = 0; i 

This solution recursively traverses the nested data structure, searching for the object with the specified 'id' property. It handles both property arrays and objects, ensuring a thorough search.

Updated Example

In the updated jsFiddle (http://jsfiddle.net/FM3qu/7/), the provided function can be used to locate the object with 'id' set to 1 in the complex data structure.

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