遍历包含所有唯一ID的多维数组

3

我有一个多维数组,但在父级和子级之间ID是唯一的,因此使用for循环遍历时会出现问题。问题是我似乎无法获取子级的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。


只用纯JavaScript?没有使用任何库吗? - qooplmao
2
你说循环有问题,具体是什么问题需要解释清楚。 - epascarello
3个回答

6
这看起来不像一个“多维数组”,而更像一棵树。使用简单的for循环可以轻松地循环一层:
for (var i=0; i<Options.length; i++) // do something

为了按顺序循环树,您需要一个递归函数:
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获取所有子元素,以便可以循环遍历这些id(无论树结构如何),请使用查找表:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接