Reputation: 35
I was faced with the question of building a tree from a flat array. We have an array.
[
{
"h1": "h001",
"h2": "z001"
},
{
"h1": "h002",
"h2": "z002"
},
{
"h1": "h003",
"h2": "z003"
}
]
I would like to get something like this:
[{
"h1": "h001",
"h2": "z001",
"children": {
"h1": "h002",
"h2": "z002",
"children": {
"h1": "h003",
"h2": "z003"
}
}
}]
Is there a way to implement this?
Thanks!
Upvotes: 2
Views: 107
Reputation: 71471
You can use recursion:
function to_tree(vals){
var v = vals.shift()
return vals.length ? {...v, children:to_tree(vals)} : v
}
var vals = [{ "h1": "h001", "h2": "z001" }, { "h1": "h002", "h2": "z002" }, { "h1": "h003", "h2": "z003" }];
console.log([to_tree(vals)])
Upvotes: 1
Reputation: 6139
This would be a great place to use the array map()
method. Essentially, we'll takin a shallow copy of the array using slice()
, then reverse()
it, then make each object a property of the previous object's under the children
property. When we are done, we re-reverse()
the array to get the original order and take the first item.
let values = [{
"h1": "h001",
"h2": "z001"
}, {
"h1": "h002",
"h2": "z002"
}, {
"h1": "h003",
"h2": "z003"
}];
let newValues = values.slice().reverse().map((e,i,a) => i ? (a[i] = { ...e, children: a[i-1] }) : a[i]).reverse()[0];
console.log(newValues);
This outputs:
{
"h1": "h001",
"h2": "z001",
"children": {
"h1": "h002",
"h2": "z002",
"children": {
"h1": "h003",
"h2": "z003"
}
}
}
Upvotes: 2
Reputation: 2473
Iterate by there index and add next node to the previous index.
Implementation:
const nodes = [{ "h1": "h001", "h2": "z001" }, { "h1": "h002", "h2": "z002" }, { "h1": "h003", "h2": "z003" }];
for (let i = 1; i < nodes.length; i++) {
nodes[i - 1].children = nodes[i];
}
console.log('solutionByIndex', nodes[0]);
Upvotes: 1