I am trying to group the array of objects based on the field hierarchy and my implementation is as follows, I have the array as follows,
[
{
"label": "AG1",
"hierarchy": "SUPER1"
},
{
"label": "AG2",
"hierarchy": "SUPER1"
},
{
"label": "MG1",
"hierarchy": "SUPER2"
},
{
"label": "MG2",
"hierarchy": "SUPER2"
},
{
"label": "SG1",
"hierarchy": "SUPER3"
}
]
Expected Output,
[
{
"label": "SUPER1",
"options": [
{
"label": "AG1",
"hierarchy": "SUPER1"
},
{
"label": "AG2",
"hierarchy": "SUPER1"
}
]
},
{
"label": "SUPER2",
"options": [
{
"label": "MG1",
"hierarchy": "SUPER2"
},
{
"label": "MG2",
"hierarchy": "SUPER2"
}
]
},
{
"label": "SUPER3",
"options": [
{
"label": "SG1",
"hierarchy": "SUPER3"
}
]
}
]
My code,
data.reduce((acc, item, i, array) => {
acc = Object.keys(acc).length ? { ...acc, "label": item['hierarchy'], "options": acc.options ?
[...acc.options, item] : [item] } : { "label": item['hierarchy'], "options": [item] };
return acc;
}, {});
But with my code, the whole array is getting under 1 hierarchy.Can anyone help me with best way out getting the desired output. Thanks.