1

我有一个如下所示的对象:

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
        }
    })
})
4

2 回答 2

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
);
于 2013-09-03T18:08:50.033 回答
0

尝试

$.each(Node.children, function(i, inode){
    $.each(inode.children, function (i2, inode2){
        if (inode2.id === 5){
            //do something
        }
    });
});
于 2013-09-03T18:06:00.413 回答