Issue
i have the following array of objects.i want to merge these objects with month as a unique id.
[
{ month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 0 },
{ month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 },
{ month: 7, openSlot: 0, confirmed: 0, requested: 0, total: 17 }
]
The above array should be merged like this
{ month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 17 },
{ month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 }
Solution
You could do this using forEach and adding the values of each key. NB: if you are interested in a more optimized code, use the solution by @Nina Scholz
const data = [
{ month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 0 },
{ month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 },
{ month: 7, openSlot: 0, confirmed: 0, requested: 0, total: 17 }
]
function merge(data) {
let tempObj = {};
data.forEach(item => {
if (tempObj[item['month']]) {
let temp = {}
Object.entries(item).forEach(([key, value]) => {
temp[key] = key === 'month' ? value : value + tempObj[item['month']][key];
})
tempObj[item['month']] = temp
} else {
tempObj[item['month']] = item
}
});
return tempObj;
}
console.log(Object.values(merge(data)));
Answered By - kiranvj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.