Home > Web Front-end > JS Tutorial > How to Find Nested Objects by Key in JavaScript?

How to Find Nested Objects by Key in JavaScript?

DDD
Release: 2024-11-16 08:52:03
Original
222 people have browsed it

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 < theObject.length; i++) {
            result = getObject(theObject[i]);
            if (result) {
                break;
            }
        }
    } else {
        for (var prop in theObject) {
            console.log(prop + ': ' + theObject[prop]);
            if (prop == 'id') {
                if (theObject[prop] == 1) {
                    return theObject;
                }
            }
            if (theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                result = getObject(theObject[prop]);
                if (result) {
                    break;
                }
            }
        }
    }
    return result;
}
Copy after login

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.

The above is the detailed content of How to Find Nested Objects by Key in JavaScript?. 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