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 を比較することです。

4

3 に答える 3

6

This does not look like a "multidimensional array", but rather like a tree. Looping one level can be done with a simple for-loop:

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

To loop the tree in-order, you will need a recursive function:

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

To get all children by their id, so that you can loop through the ids (regardless of the tree structure), use a lookup table:

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

…and to loop them sorted by id, you now can do

Object.keys(nodesById).sort(function(a,b){return a-b;}).forEach(function(id) {
    var node = nodesById[id];
    // do something
});
于 2012-12-19T00:46:13.323 に答える
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);
于 2012-12-19T00:44:16.377 に答える
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);
于 2012-12-19T00:44:29.837 に答える