I’m trying to add cumulative values in my JSON object. When I tried using reduce it’s summing up all the values of particular key value. How can I achieve my desired output?
Sample JSON
[{
"id": 28,
"Title": "A",
"Price": 10
}, {
"id": 56,
"Title": "AB",
"Price": 10
}, {
"id": 89,
"Title": "ABC",
"Price": 10
}]
required output
[{
"id": 28,
"Title": "A",
"Total_Spent": 10 (Sum of A)
}, {
"id": 56,
"Title": "AB",
"Total_Spent": 20 (sum of A+AB)
}, {
"id": 89,
"Title": "ABC",
"Total_Spent": 30 (sum of A + AB + ABC)
},
.......]
Advertisement
Answer
Have a variable to hold the cumulative sum; map each original item to a new one, deconstructing the original and constructing the new item, with Total_Spent having the value of the cumulative sum, which gets updated with each item’s price.
const data = [{
"id": 28,
"Title": "A",
"Price": 10
}, {
"id": 56,
"Title": "AB",
"Price": 10
}, {
"id": 89,
"Title": "ABC",
"Price": 10
}];
let cumsum = 0;
const newData = data.map(({id, Title, Price}) => ({id, Title, Total_Spent: cumsum += Price}));
console.log(newData);