I currently have an array of objects which I'm trying to reshape into a nested object with the ID as an object key, and target that ID with the parent id if it's not "0". I've tried several approaches but I'm struggling big time! The main stumbling block for me is anything beyond one or two layers deep. Ideally I need this to be dynamic so it can handle potentially any depth although in the wild I doubt it will go beyond 3 layers.
Here is the incoming array of objects:
[
{
ID: "1671",
parent: "0",
},
{
ID: "1223",
parent: "0",
},
{
ID: "1668",
parent: "0",
},
{
ID: "1688",
parent: "0",
},
{
ID: "1669",
parent: "0",
},
{
ID: "1681",
parent: "1669",
},
{
ID: "1680",
parent: "1669",
},
{
ID: "1670",
parent: "1669",
},
{
ID: "1682",
parent: "1669",
},
{
ID: "1433",
parent: "1682",
},
{
ID: "1684",
parent: "1682",
},
{
ID: "1672",
parent: "1684",
},
{
ID: "1685",
parent: "1672",
},
{
ID: "1686",
parent: "1672",
},
{
ID: "1683",
parent: "0",
},
{
ID: "1230",
parent: "0",
},
{
ID: "1667",
parent: "0",
},
{
ID: "1687",
parent: "0",
}
];
And here is the desired transformation:
1671: {
ID: "1671",
parent: "0",
},
1223: {
ID: "1223",
parent: "0",
},
1668: {
ID: "1668",
parent: "0",
},
1688: {
ID: "1688",
parent: "0",
},
1669: {
ID: "1669",
parent: "0",
children: {
1681: {
ID: "1681",
parent: "1669",
},
1680: {
ID: "1680",
parent: "1669",
},
1670: {
ID: "1670",
parent: "1669",
},
1682: {
ID: "1682",
parent: "1669",
children: {
1433: {
ID: "1433",
parent: "1682",
},
1684: {
ID: "1684",
parent: "1682",
children: {
1672: {
ID: "1672",
parent: "1684",
children: {
1685: {
ID: "1685",
parent: "1672",
},
1686: {
ID: "1686",
parent: "1672",
}
}
}
}
}
}
}
}
},
1683: {
ID: "1683",
parent: "0",
},
1230: {
ID: "1230",
parent: "0",
},
1667: {
ID: "1667",
parent: "0",
},
1687: {
ID: "1687",
parent: "0",
}
Most of my failed approaches have been using Array.reduce() and other types of recursion but to no avail, so I'm interested to see if there is a solution for this.
Thanks