简体   繁体   中英

Creating a hierarchical tree in javascript

I have a flat array like this containing data objects with id and values. Every id will be unique

var data = [{
        id: 1,
        value: 'as',
        parent: 2
    }, {
        id: 2,
        value: 'sasa',
        parent: 3
    }, {
        id: 3,
        value: 'sasa',
        parent: 
    }]

How can I create a hierarchical tree like "object" in JavaScript not an Array because I further want to access the object's elements like 3.2.value

{
        id: 3,
        value: 'sasa',
        parent: '',
        2: {
            id: 2,
            value: 'sasa',
            parent: 3,
            1: {
                id: 1,
                value: 'as',
                parent: 2
            }
        }
    }

You could take an iterative approach by using an object for collencting an create an object for id and parent at the same time to keep their relation.

At the end return the property which has the root as parent.

The result is lightly different, because you want to address the nodes by using their id as accessor.

 var data = [{ id: 1, value: 'as', parent: 2 }, { id: 2, value: 'sasa', parent: 3 }, { id: 3, value: 'sasa', parent: '' }], tree = function (data, root) { return data.reduce(function (r, o) { Object.assign(r[o.id] = r[o.id] || {}, o); r[o.parent] = r[o.parent] || {}; r[o.parent][o.id] = r[o.id]; return r; }, Object.create(null))[root]; }(data, ''); console.log(tree);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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