How do I group nested arrays like this.
[
{
"_id": "Id",
"name": "Product Name",
"Departments": [
{
"_id": "63c0faf4752a6a7cfd169602",
"name": "Audio",
"parentId": null
},
{
"_id": "63c0faf4752a6a7cfd16960c",
"name": "Home Audio & Speakers",
"parentId": "63c0faf4752a6a7cfd169602"
},
{
"_id": "63c0faf4752a6a7cfd16960d",
"name": "Speakers",
"parentId": "63c0faf4752a6a7cfd16960c"
}
],
},
{
"_id": "Id",
"name": "Product Name",
"Departments": [
{
"_id": "63c0faf4752a6a7cfd169957",
"name": "Computers & Accessories",
"parentId": null
},
{
"_id": "63c0faf4752a6a7cfd16996c",
"name": "Data Storage",
"parentId": "63c0faf4752a6a7cfd169957"
},
{
"_id": "63c0faf4752a6a7cfd16996e",
"name": "SSD",
"parentId": "63c0faf4752a6a7cfd16996c"
}
],
},
{
"_id": "Id",
"name": "Product Name",
"Departments": [
{
"_id": "63c0faf4752a6a7cfd169602",
"name": "Audio",
"parentId": null
},
{
"_id": "63c0faf4752a6a7cfd16960c",
"name": "Home Audio & Speakers",
"parentId": "63c0faf4752a6a7cfd169602"
},
{
"_id": "63c0faf4752a6a7cfd16960d",
"name": "AV Receivers",
"parentId": "63c0faf4752a6a7cfd16960c"
}
],
]
Into this. I want them to be grouped by their department names and getting only the 2nd item of the array. I tried doing different approaches and I still can’t manage to do it. Can anyone help me with this.
{
ShopDepartments: [
{
"_id": "63c0faf4752a6a7cfd16960c",
"name": "Home Audio & Speakers",
"parentId": "63c0faf4752a6a7cfd169602"
},
{
"_id": "63c0faf4752a6a7cfd16996c",
"name": "Data Storage",
"parentId": "63c0faf4752a6a7cfd169957"
},
]
}