Reputation: 95
I have an object that looks like the following:
Node{
name: "root",
level: 0,
children: Array[14],
parent: null,
id: 0
}
And inside Node.children
...
Node.children[
{
name: "child1",
level: 1,
children: Array[1],
parent: root,
id: 1
},
{
name: "child2",
level: 1,
children: Array[1],
parent: root,
id: 2
},
{
name: "child3",
level: 1,
children: Array[2],
parent: root,
id: 3
},
]
And inside Node.children[1].children ...
Node.children[1].children[
{
name: "child1-1",
level: 2,
children: Array[0],
parent: child1,
id: 4
}
]
What I need is to loop through the Node object and try and match every "id
" with a value given. For example...
$.each(Node, function(i, nodes){
$.each(nodes, function (i2, nodes2){
if (nodes2.id == 5){
//do something
}
})
})
Upvotes: 1
Views: 86
Reputation: 17238
try
$.each(Node.children, function(i, inode){
$.each(inode.children, function (i2, inode2){
if (inode2.id === 5){
//do something
}
});
});
Upvotes: 0
Reputation: 36438
You'll want a function you can call recursively:
function checkNode(node, action, id) {
if (node.id === id)
action(node);
var kids = node.children || [];
$.each( kids,
function(i,n) {
checkNode(n, action, id);
}
);
}
called as:
checkNode(
node,
function(n) { alert(n.name); },
5
);
Upvotes: 1