2012-12-19 61 views
3

我有一个多维数组,但ID在父母和孩子中是唯一的,所以我通过使用for循环来循环使用问题。问题是我似乎无法抓住孩子的ID。你认为我应该如何处理?通过具有所有唯一ID的多维数组遍历多个数组

var Options = [ 
      { 
       id: 0, 
       children: [] 
      }, 
      { 
       id: 2, 
       children: [] 
      }, 
      { 
       id: 3, 
       children: [ 
        { 
         id: 4, 
         children: [] 
        }, 
        { 
         id: 5, 
         children: [] 
        }, 
        { 
         id: 6, 
         children: [] 
        } 
       ] 
      }, 
      { 
       id: 7, 
       children: [ 
        { 
         id: 8, 
         children: [] 
        }, 
        { 
         id: 9, 
         children: [] 
        } 
        ] 
      } 
     ]; 

我一直代码简洁为简洁起见。我想要做的是遍历数组来比较ID的。

+0

只是纯粹的JavaScript?没有图书馆? – qooplmao

+2

你是什么意思你有问题循环?你需要解释你的问题是什么。 – epascarello

回答

5

这看起来并不像一个 “多维数组”,而是像一棵树。

for (var i=0; i<Options.length; i++) // do something 

要循环树顺序,你将需要一个递归函数:循环一层可以用for循环的简单做

function loop (children, callback) { 
    for (var i=0; i<children.length; i++) { 
     callback(children[i]); 
     loop(children[i].children, callback); 
    } 
} 
loop(Options, console.log); 

要通过自己的ID得到所有的孩子,这样就可以通过IDS(无论树形结构)的循环,可使用查找表:

var nodesById = {}; 
loop(Options, function(node) { 
    nodesById[node.id] = node; 
}); 
// access: 
nodesById[4]; 

...和循环他们通过ID进行排序,你现在可以做

Object.keys(nodesById).sort(function(a,b){return a-b;}).forEach(function(id) { 
    var node = nodesById[id]; 
    // do something 
}); 
2

递归怎么样?

var findById = function (arr, id) { 
    var i, l, c; 
    for (i = 0, l = arr.length; i < l; i++) { 
     if (arr[i].id === id) { 
      return arr[i]; 
     } 
     else { 
      c = findById(arr[i].children, id); 
      if (c !== null) { 
       return c; 
      } 
     } 
    } 
    return null; 
} 

findById(Options, 8); 
2

啊,使用递归:d

var Options = "defined above";//[] 
var OptionArray = []; //just as an example (not sure what you want to do after looping) 
(function looper(start){ 
for(var i = 0, len = start.length; i < len; i++){ 
    var currentOption = start[i]; 
    if(currentOption.id > 3){//could be more complex 
    OptionArray.push(currentOption); 
    } 
    if(currentOption.children.length > 0){ 
    looper(currentOption.children); 
    } 
} 
})(Options);