Here is the JSON data that I have:
{"rows":[
{"shiftId":1,"shift":"Morning","item":"Tea","value":20},
{"shiftId":1,"shift":"Morning","item":"Coffee","value":30},
{"shiftId":2,"shift":"Evening","item":"Tea","value":40},
{"shiftId":2,"shift":"Evening","item":"Coffee","value":35}
]}
I want to merge entries with the same shift, add their values together, and create a new object for each item. The desired output should look like this:
{"rows":[
{
"shiftId":1,
"shift":"Morning",
"item":[{"itemName":"Tea"},{"itemName":"Coffee"}],
"value":50
},
{
"shiftId":2,
"shift":"Evening",
"item":[{"itemName":"Tea"},{"itemName":"Coffee"}],
"value":75
}
]}
I attempted to achieve this using the following code:
var merged = {rows: []};
data.forEach(function (source) {
if (!merged.rows.some(function (row) {
return row.shiftId == source.shiftId;
})) {
merged.rows.push({
shiftId: source.shift,
shift: source.shift,
item: [{
itemName: source.shift
}],
value: source.value
});
} else {
var existRow = merged.rows.filter(function (existRow) {
return existRow.shiftId == source.shiftId
})[0];
existRow.total += source.total; // There was an error here, it should be "existRow.value += source.value"
existRow.item = source.item.push(existRow.item);
}
});
However, this code is not functioning as expected. Thank you in advance for your help.