Search code examples
javascriptarraysalgorithmtreehierarchy

Construct flat array from tree of objects


Suppose I have a tree of objects like the following, perhaps created using the excellent algorithm found here: https://stackoverflow.com/a/22367819/3123195

{
    "children": [{
        "id": 1,
        "title": "home",
        "parent": null,
        "children": []
    }, {
        "id": 2,
        "title": "about",
        "parent": null,
        "children": [{
            "id": 3,
            "title": "team",
            "parent": 2,
            "children": []
        }, {
            "id": 4,
            "title": "company",
            "parent": 2,
            "children": []
        }]
    }]
}

(Specifically in this example, the array returned by that function is nested as the children array property inside an otherwise empty object.)

How would I convert it back to a flat array?


Solution

  • Hope your are familiar with es6:

    let flatten = (children, extractChildren) => Array.prototype.concat.apply(
      children, 
      children.map(x => flatten(extractChildren(x) || [], extractChildren))
    );
    
    let extractChildren = x => x.children;
    
    let flat = flatten(extractChildren(treeStructure), extractChildren)
                   .map(x => delete x.children && x);
    

    UPD:

    Sorry, haven't noticed that you need to set parent and level. Please find the new function below:

    let flatten = (children, getChildren, level, parent) => Array.prototype.concat.apply(
      children.map(x => ({ ...x, level: level || 1, parent: parent || null })), 
      children.map(x => flatten(getChildren(x) || [], getChildren, (level || 1) + 1, x.id))
    );
    

    https://jsbin.com/socono/edit?js,console