1

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
            }
        }
    }
3
  • 1
    Possible duplicate of Build tree array from flat array in javascript Commented Nov 8, 2018 at 14:06
  • That is different I already saw that answer but that answer seems to deal with arrays I want the object implementation Commented Nov 8, 2018 at 14:14
  • id: 3 should have parent: ''. Commented Nov 8, 2018 at 14:25

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

and how fast is it? but anyway, the approach is not optimised for speed, but for better reading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.