How to convert the given list to a tree?

  • 0
    I am experiencing difficulty with how to make a hierarchical structure from this list ... the main node from which to build the tree is not explicitly indicated here. How can you define it?
    const data = [
    	{ id: 'main', parts: ['main-left', 'main-right'] },
    	{ id: 'main-101', parts: undefined },
    	{ id: 'main-102', parts: undefined },
    	{ id: 'main-head', parts: undefined },
    	{ id: 'main-left', parts: ['main-101', 'main-102'] },
    	{ id: 'main-right', parts: ['main-head'] },
    ];

    I receive data in this format from a database, and I need to display it in the form of a tree
    JavaScript Anonymous, Sep 9, 2020

  • 2 Answers
  • 0
    function createTree(arr) {
    const tree = Object.fromEntries(arr.map(({ parts, ...n }) => [ n.id, n ]));
    arr.forEach(n => tree[n.id].children = n.parts?.map(m => tree[m]) ?? []);
    return Object.values(tree).filter(n => arr.every(m => !m.parts?.includes(n.id)));
    }
    Anonymous

  • 0
    Which never appears in parts - that is the root
    Ella Gray

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!