簡體   English   中英

如何遞歸獲取嵌套對象中所有子項的列表?

[英]How to recursively get a list of all children in a nested object?

假設我有一個可以容納其自身其他實例的類:

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添加到一些rootThingsubThings

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 S和他們所有的subThing S IN 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));

感謝@zerkms,這是一個有效的實現:

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

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

    return allChildren;
}

您是否正在尋找這樣的東西?

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對象處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM