0

I have below JavaScript object pattern.

{
    "_id": 2,
    "children": [
    {
        "_id": 3,
        "children": [
        {
            "_id": 5,
            "children": [
            {
                "_id": 9,
                "children": [],
                "id_category": 9,
                "parent_id": 5
            },
            {
                "_id": 10,
                "children": [],
                "id_category": 10,
                "parent_id": 5
            }],
            "id_category": 5,
            "parent_id": 3
        },
        {
            "_id": 6,
            "children": [],
            "id_category": 6,
            "parent_id": 3
        }],
        "id_category": 3,
        "parent_id": 2
    },
    {
        "_id": 4,
        "children": [
        {
            "_id": 7,
            "children": [],
            "id_category": 7,
            "parent_id": 4
        },
        {
            "_id": 8,
            "children": [],
            "id_category": 8,
            "parent_id": 4
        }],
        "id_category": 4,
        "parent_id": 2
    }],
    "id_category": 2,
    "parent_id": 1
}

Now I want to get whole data for which I pass the value of _id. For example if I pass 5, it will return the whole object of 5

{
    "_id": 5,
    "children": [
    {
        "_id": 9,
        "children": [],
        "id_category": 9,
        "parent_id": 5
    },
    {
        "_id": 10,
        "children": [],
        "id_category": 10,
        "parent_id": 5
    }],
    "id_category": 5,
    "parent_id": 3
}

The problem is Level of nesting is unlimited .

Please suggest.

pkd
  • 504
  • 5
  • 13

1 Answers1

0

Use a recursive function.

Something like this (untested, but should be ok)

function search(value, tree) {
    if (tree._id === value)
        return value;

    var numChildren = tree.children.length;
    for (var i = 0; i < numChildren; ++i) {
        var result = search(value, tree.children[i]);
        if (result)
            return result;
    }

    return null;
}

var tree = {...your big json hash...};
var found = search(5, tree);

console.log(found);
Eloims
  • 5,106
  • 4
  • 25
  • 41