如何递归获取嵌套对象中所有子项的列表?

时间:2015-04-07 01:17:22

标签: javascript recursion

假设我有一个可以容纳其他实例的类:

function Thing() {
    this.subThings = [];
}

我将n subThings添加到最重要的内容:

var rootThing = new Thing();

rootThing.subThings.push(new Thing());
rootThing.subThings.push(new Thing());
rootThing.subThings.push(new Thing());

然后我将n subThings添加到rootThing subThings的某些rootThing.subThings[0].subThings.push(new Thing()); rootThing.subThings[0].subThings.push(new Thing()); rootThing.subThings[0].subThings.push(new Thing()); 中:

rootThing
|
+--subThing
|  |
|  +--subThing
|  |
|  +--subThing
|  |
|  +--subThing
|
+--subThing
|
+--subThing

此时,结构如下所示:

subThing

那么,如何在subThing中获取所有rootThing和所有 function getAllChildren(beginNode) { var allChildren = []; beginNode.subThings.forEach(function(childNode) { allChildren.push(childNode); // allChildren = allChildren.concat(childNode.subThings); // something along these lines }); return allChildren; } console.log(getAllChildren(rootThing)); 的列表?

{{1}}

2 个答案:

答案 0 :(得分:1)

感谢@zerkms,这是一个有效的实现:

function getAllChildren(beginNode) {
    var allChildren = beginNode.subThings;

    beginNode.subThings.forEach(function(childNode) {
        allChildren = allChildren.concat(getAllChildren(childNode));
    });

    return allChildren;
}

答案 1 :(得分:0)

你在找这样的东西吗?

var GetAllThings = function(Thing thing) {
    var result = [];

    //Assume you want to remove the subthings as you flatten
    var subthings = thing.subthings;
    thing.subThings = null;

    result.push(thing);

    for(var i = 0; i < subthings i++) {
        result.concat(GetAllThings(subthings[i]));
    }

    return result;
};

这基本上会使树变平,但如果您只是想查看/处理它,上面的注释是正确的,因为您可以将其作为json对象来处理。