Reputation: 58
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
}
}
}
Upvotes: 1
Views: 981
Reputation: 386519
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; }
Upvotes: 1