I have an array of objects coming from backend.
var values = [
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization ABC",
"value": 3
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization ABC",
"value": 2.5
}
]
},
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization XYZ",
"value": 2.5
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization XYZ",
"value": 3.3
}
]
},
];
I want to combine the inner array’s objects and get one single array of objects for same name of objects.
var output = [
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization ABC",
"value": 3
},
{
"name": "Organization XYZ",
"value": 2.5
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization ABC",
"value": 2.5
},
{
"name": "Organization XYZ",
"value": 3.3
}
]
},
];
I think, I need to use reduce but not sure how I can combine objects of series of same name.
Please help and guide. Thanks
>Solution :
You are right with reducer
var values = [
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization ABC",
"value": 3
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization ABC",
"value": 2.5
}
]
},
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization XYZ",
"value": 2.5
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization XYZ",
"value": 3.3
}
]
},
];
var result = values.reduce((acc, curr) => {
var existing = acc.find(element => element.name === curr.name);
if(existing) {
existing.series.push(...curr.series);
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result);