let list=[{key1,children[]},{key2,children[]},{key3,children[]}]
How to get an array like this with javascript?
list1=[{key1,children[{key2,children[{key3,children[]}]}]}
I tried like this
for (let i = 0; i < list.length; i++) {
if (list[i + 1]) {
list[0].children.push(list[i + 1]);
}
}
but its pushing all children into list[0].children
3
Answers
You’ll need to process your original list in reverse order, something like this should do it:
Here is an alternative solution to Jamiec answer.
When the data is transformed, it does not mutate
list
, since astructuredClone
is created. I also reduced right-to-left, because when theindex
reaches0
, we will just return[item
]. We do need to set a non-undefined
value for the reducer initialized value. The valuenull
will work.While the
index
is greater than0
, push theitem
as achild
to the left of it.@Jamiec, instead of reversing the list, you can change the indexing. Be careful, this still modifies the original
list
array!Avoid
structuredClone()
at all costs since it’s a slow way to clone objects unless you want object references preserved. UseJSON.parse(JSON.stringify(object))
rather on data acting as data, not as a functional object.For your case if you want a copy of the data, just create your custom
clone()
function:And a benchmark against
structuredClone()
: 33x faster: