Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested JSON find item

I have the following valid JSON. It describes a tree structure:

{
"items": [
    {
        "id": "d1"
    },
    {
        "id": "2",
        "children": [
            {
                "id": "3"
            },
            {
                "id": "4"
            },
            {
                "id": "5",
                "children": [
                    {
                        "id": "6"
                    },
                    {
                        "id": "7",
                        "children": [
                            {
                                "id": "8"
                            },
                            {
                                "id": "9"
                            }
                        ]
                    },
                    {
                        "id": "10"
                    }
                ]
            },
            {
                "id": "11"
            },
            {
                "id": "12"
            }
        ]
    },
    {
        "id": "13"
    },
    {
        "id": "14"
    }
]
}

I need to be able to get any of the "items" by id and any of the child items. For example. Initially I tried grep:

var returnedData = $.grep(obj.items, function(element, index){return element.id == "2";
});

This worked great for item with id==2 but fails completely when I try to obtain element.id=="7"

Any assistance would be appreciated. Thanks in advance.

like image 364
user831839 Avatar asked Apr 14 '26 14:04

user831839


1 Answers

You can make a recursive function to search in the data:

function find(source, id)
{
    for (key in source)
    {
        var item = source[key];
        if (item.id == id)
            return item;

        // Item not returned yet. Search its children by recursive call.
        if (item.children)
        {
            var subresult = find(item.children, id);

            // If the item was found in the subchildren, return it.
            if (subresult)
                return subresult;
        }
    }
    // Nothing found yet? return null.
    return null;
}

// In the root object, the array of items is called 'items', so we pass in 
// data.items to look into. The root object itself doesn't seem to have an id anyway.
var result = find(data.items, 7);

// Show the name of item 7, if it had one... 
alert(result.name);

Demo: http://jsfiddle.net/rj26H/

In this function I just looped over the object, so its a bit more verbose. You could probably also use $.grep to do the searching and make the code a bit smaller. Anyway, the trick is to search all children if the item is not found on the main level. Apparently grep doesn't work in a recursive fashion.

like image 181
GolezTrol Avatar answered Apr 17 '26 03:04

GolezTrol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!