我有一个如下所示的对象:
Node{
name: "root",
level: 0,
children: Array[14],
parent: null,
id: 0
}
在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
},
]
在Node.children [1] .children ...
中Node.children[1].children[
{
name: "child1-1",
level: 2,
children: Array[0],
parent: child1,
id: 4
}
]
我需要的是遍历Node对象并尝试将每个“id
”与给定的值匹配。例如......
$.each(Node, function(i, nodes){
$.each(nodes, function (i2, nodes2){
if (nodes2.id == 5){
//do something
}
})
})
答案 0 :(得分:1)
你需要一个可以递归调用的函数:
function checkNode(node, action, id) {
if (node.id === id)
action(node);
var kids = node.children || [];
$.each( kids,
function(i,n) {
checkNode(n, action, id);
}
);
}
称为:
checkNode(
node,
function(n) { alert(n.name); },
5
);
答案 1 :(得分:0)
试
$.each(Node.children, function(i, inode){
$.each(inode.children, function (i2, inode2){
if (inode2.id === 5){
//do something
}
});
});