I've got some nested object data and I want to search it and return the matching object based on the id.
var data = [{id: 0, name: 'Template 0', subComponents:[
{id: 1, name: 'Template 1', subItems:[
{id: 2, name: 'Template 2', subComponents:[{id: 3, name: 'Template 3'}], subItems: [{id: 4, name: 'Template 4'}]}
]}
]}
];
So I want to do something like this
getObjectByKeyValue({id: 3})
and have it return
{id: 3, name: 'Template 3'}
It's sort of got to be done generically because I have subItems, AND subComponents which could each have children.
I tried this using Prototype 1.7 and no luck - I think this just searches an array, and not a tree with it's sub nodes:
data.find(function(s){return s.id == 4;})
Thanks in advance!!!!!!
Please see my solution below or http://jsfiddle.net/8Y6zq/:
In this implementation we can use search by KEY or SELECTOR (eg.
"<paren_key>.<child_key_1>.<child_key_2>. ... <child_key_N>"
)In case you really need a search through your tree data return all results (not a unique key), here is a little modified version of mVChr's answer:
I went a slightly different route and made the
findKey
method an Object protype:Which you would call directly on the data object, passing in the key/value you're looking for:
Note that this function allows you to find an object based on any key:
See example → (open console to view result)
Not the best of the and final solution. But can get you a start for what you are looking...