I am getting below response, I want to ReGroup all the data and its children based on buSubRegion which is present inside children now. And also needs to add buSubRegion outside children.
For EX - In below Response, 1UL Africa belongs to Africa object and also present inside Europe object, so i need to merge children of all objects which belongs to 1UL Africa into one array of object.
I want if buSubRegion have a same value and it is present inside many objects then find all those objects and merge into one.
Also, Agbara - Savoury dont have a BU sub-region So i don't want to include this object.
Can anyone please help me to achieve this.
const data = [
{
"name": "Africa",
"id":1,
"children": [
{
"name": "Agbara - Laundry",
"buSubRegion": "1UL Africa",
"children": [
{
'lineId':"R_D005_TPKDST02"
}
]
},
{
"name": "Agbara - Savoury",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"name": "Europe",
"id":2,
"children": [
{
"name": "Europe1",
"buSubRegion": "1UL Africa",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
},
{
"name": "Europe2",
"buSubRegion": "Test Europe",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"name": "Latem",
"id":3,
"children": [
{
"name": "test1",
"buSubRegion": "latem1",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
}
];
Below is my Expected Output
[
{
"buSubRegion": "1UL Africa",
"name": "Africa",
"id":1,
"children": [
{
"name": "Agbara - Laundry",
"buSubRegion": "1UL Africa",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
},
{
"name": "Europe1",
"buSubRegion": "1UL Africa",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"buSubRegion": "Test Europe",
"name": "Europe",
"id":2,
"children": [
{
"name": "Europe2",
"buSubRegion": "Test Europe",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"name": "Latem",
"buSubRegion": "latem1",
"id":3,
"children": [
{
"name": "test1",
"buSubRegion": "latem1",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
}
];
I tried below code which was working perfectly and also giving output as per my expectation, But don't know why it was throwing error in Angular Typescript and not returning any output. I am getting error in below line for ??= and semicolon ; Also i guess foreach is not supporting in typescript.
Can anyone help to make my code working
const result = data.reduce((a,{children, ...rest})=>{
children.forEach(({buSubRegion,...others})=>{
if(buSubRegion){
a[buSubRegion] ??= {buSubRegion, ...rest, children:[]};
a[buSubRegion].children.push({buSubRegion, ...others})
}
});
return a;
},{});
console.log(Object.values(result));