简体   繁体   中英

trying to recursively create an array of results from a json tree-like structure JavaScript

I'm trying to get a list of the descendants for a specific person. Below is what i have so far:

function getDescendants(id, descendants){
    children = getChildren(id);
    if(children){
        for (var child in children) {
           if(children.hasOwnProperty(child)){
               descendants.push(getDescendants(children[child].id, descendants));
           }
        }
    }
    return getPersonById(id);
}

This works until it returns to the initial call and has forgotten the children array.

getChildren returns and array of child objects getPersonById returns a person object

Any help/suggestions are appreciated

function getDescendants(id, descendants, originalChildren ){
    children = getChildren(id);
    if(children){
        var originalChildren = originalChildren || children;
        for (var child in children) {
           if(children.hasOwnProperty(child)){
               descendants.push(getDescendants(children[child].id, descendants, originalChildren ));
           }
        }
    }
    return getPersonById(id);
}

When you first call getDescendants pass null or just don't pass anything in the third slot. If it's null then it will store the value of children in the variable otherwise it'll store originalChildren each time and you'll keep passing that first instance of children through your function.

After consulting some co-workers and a lot of brain pain this is what we came up with.

let getDescendants = (parentID, people) => {
    return people.filter((el)=>{
        return el.parents.indexOf(parentID) > -1;
    }).map((kid)=>{
        return [...getDescendants(kid.id, people), kid.id ];
    }).reduce((a, b) => {
        return a.concat(b);
    }, []);
}

Thank you all for the assistance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM