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

How to Find Objects in Nested Arrays by Key Using Recursion?

DDD
DDDOriginal
2024-11-19 17:55:021048browse

How to Find Objects in Nested Arrays by Key Using Recursion?

Finding Objects in Nested Arrays by Key

When working with complex nested data structures, it's often necessary to locate a specific object based on a key. This can be challenging, especially when the data is deeply nested.

Recursion to the Rescue

Recursion allows us to navigate through nested data by breaking it down into smaller, manageable chunks. Here's a recursive function that can find an object with a given key:

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) {
            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;
}

Usage Example

Let's use this function to find the object where id is 1 in the example nested array:

var myArray = [{
    'title': "some title",
    'channel_id': '123we',
    'options': [{
        'channel_id': 'abc',
        'image': 'http://asdasd.com/all-inclusive-block-img.jpg',
        'title': 'All-Inclusive',
        'options': [{
            'channel_id': 'dsa2',
            'title': 'Some Recommends',
            'options': [{
                'image': 'http://www.asdasd.com',
                'title': 'Sandals',
                'id': '1',
                'content': {
                    // ...
                }
            }]
        }]
    }]
}];

var result = getObject(myArray);
console.log(result); // prints the found object

The above is the detailed content of How to Find Objects in Nested Arrays by Key Using Recursion?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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