There is an array with the following data
Initial data
const data = [
{
type: 'first'
stats: [
{name: 'yes', value: 11},
{name: 'no', value: 33},
]
},
{
type: 'second',
stats: [
{name: 'call back', value: 32},
{name: 'no', value: 77},
]
},
{
type: 'third',
stats: [
{name: 'yes', value: 14},
]
}
]
I need help to convert data above to the next form
Expected result
const dataTransformed = [
{
type: 'first',
stats: [
{name: 'yes', value: 11},
{name: 'no', value: 33},
{name: 'call back', value: 0},//*zero because this object exist in third object but here doesnt
]
},
{
type: 'second',
stats: [
{name: 'yes', value: 0},//*zero because this object exist in first object but here doesnt
{namename: 'no', value: 77},
{name: 'call back', value: 32},
]
},
{
type: 'third',
stats: [
{name: 'yes', value: 14},
{name: 'no', value: 0},//*zero because this object exist in first object but here doesnt
{name: 'call back', value: 0},//*zero because this object exist in first object but here doesnt
]
}
]
That is, it is necessary that in each object in the stats array the order of objects with the specified name corresponds to other objects, while if an object with the same name there is no corresponding index, you need to create it with empty value.
const data=[{type:"first",stats:[{name:"yes",value:11},{name:"no",value:33}]},{type:"second",stats:[{name:"call back",value:32},{name:"no",value:77}]},{type:"third",stats:[{name:"yes",value:14}]}];
const names = [... new Set(data.reduce((a, x) => a.concat(x.stats.map(y => y.name)), []))];
const dataTransformed = data.map(x => ({
...x,
stats: names.map(name => ({
name,
value: (x.stats.find(z => z.name === name) || {value: 0}).value,
})),
}));
console.log(dataTransformed);
You can create an array of names, then check which names are presented in stats, using an default value when its not