Estoy intentando agrupar un array de objetos a partir de un parentId
que trae cada elemento del array, el resultado que espero es el que tengo en el output.
He hecho el primer nivel y me crea bien el primer subgrupo de chlds
pero no veo la forma de que me genere los siguientes. Gracias de antemano!
Input
const data = [
{
"groupid": 1,
"parentid": 0,
"usrdesc": "Principal"
},
{
"groupid": 43,
"parentid": 1,
"usrdesc": "Opers"
},
{
"groupid": 44,
"parentid": 43,
"usrdesc": "London"
},
{
"groupid": 45,
"parentid": 44,
"usrdesc": "Sells"
},
{
"groupid": 46,
"parentid": 45,
"usrdesc": "grp"
},
{
"groupid": 89,
"parentid": 46,
"usrdesc": "PFG"
},
{
"groupid": 48,
"parentid": 44,
"usrdesc": "WEF"
},
{
"groupid": 49,
"parentid": 44,
"usrdesc": "API"
},
{
"groupid": 50,
"parentid": 49,
"usrdesc": "CTX"
},
{
"groupid": 142,
"parentid": 44,
"usrdesc": "CSS"
},
{
"groupid": 58,
"parentid": 1,
"usrdesc": "ASD"
},
{
"groupid": 71,
"parentid": 58,
"usrdesc": "CZX"
},
{
"groupid": 106,
"parentid": 58,
"usrdesc": "RTE"
},
{
"groupid": 140,
"parentid": 58,
"usrdesc": "NIO"
},
{
"groupid": 148,
"parentid": 58,
"usrdesc": "ADGB"
},
{
"groupid": 62,
"parentid": 1,
"usrdesc": "OUS"
},
{
"groupid": 136,
"parentid": 1,
"usrdesc": "BGE"
},
{
"groupid": 137,
"parentid": 136,
"usrdesc": "PDS"
},
{
"groupid": 138,
"parentid": 136,
"usrdesc": "DVE"
}
]
OUTPUT
const response = [
{
"groupid": 1,
"parentid": 0,
"usrdesc": "Principal",
"chlds": [
{
"groupid": 43,
"parentid": 1,
"usrdesc": "Opers",
"chlds": [
{
"groupid": 44,
"parentid": 43,
"usrdesc": "London",
"chlds": [
{
"groupid": 45,
"parentid": 44,
"usrdesc": "Sells",
"chlds": [
{
"groupid": 46,
"parentid": 45,
"usrdesc": "grp",
"chlds": [
{
"groupid": 89,
"parentid": 46,
"usrdesc": "PFG"
}
]
}
]
},
{
"groupid": 48,
"parentid": 44,
"usrdesc": "WEF"
},
{
"groupid": 49,
"parentid": 44,
"usrdesc": "API",
"chlds": [
{
"groupid": 50,
"parentid": 49,
"usrdesc": "CTX"
}
]
},
{
"groupid": 142,
"parentid": 44,
"usrdesc": "CSS"
}
]
}
]
},
{
"groupid": 58,
"parentid": 1,
"usrdesc": "ASD",
"chlds": [
{
"groupid": 71,
"parentid": 58,
"usrdesc": "CZX"
},
{
"groupid": 106,
"parentid": 58,
"usrdesc": "RTE"
},
{
"groupid": 140,
"parentid": 58,
"usrdesc": "NIO"
},
{
"groupid": 148,
"parentid": 58,
"usrdesc": "ADGB"
}
]
},
{
"groupid": 62,
"parentid": 1,
"usrdesc": "OUS"
},
{
"groupid": 136,
"parentid": 1,
"usrdesc": "BGE",
"chlds": [
{
"groupid": 137,
"parentid": 136,
"usrdesc": "PDS"
},
{
"groupid": 138,
"parentid": 136,
"usrdesc": "DVE"
}
]
}
]
}
]
Mi código
const nested = data.reduce((acc, item) => {
if (item.parentid === 0) {
return [...acc, item];
} else {
const parentIndex = acc.findIndex(parent => parent.groupid === item.parentid);
const parent = acc[parentIndex];
if (parentIndex >= 0) {
const children = parent.children ?? [];
return Object.assign([], acc, {
[parentIndex]: {
...parent,
children: [...children, item],
},
});
}
return acc
}
}, []);