Lets say I have the following array of objects which have parent child relations:
[
{ A1: [ "B1" ] },
{ B1: [ "C11", "C12", "C13" ] },
{ C11: [ "D100", "D111", "D112", "D113", "D131" ] },
{ D100: [ "E1000", "E1100" ] }
]
How can I convert the above array to a nested object to represent the relations?
So the target object would be:
{
A1:
{
B1:
{
C11:
{
D100: ["E1000", "E1100"],
D111: [],
D112: [],
D113: [],
D131: []
},
C12: [],
C13: []
}
}
}
I tried several recursive approaches with reduce etc. but still struggle to get all levels converted correctly.
2
Answers
Assuming an object with same pattern, you could takean object with references to the neste objects.
If you like to get different values, like arrays instead of objects, you could specify this in the inout data.
You can achieve the desired result using recursion. Maybe my example is a bit clunky, but it does the trick: