jquery循环(.each)

时间:2013-09-03 17:58:59

标签: javascript jquery arrays each

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

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

2 个答案:

答案 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
        }
    });
});