I have the following array:
var curr = [{ "Year": 2019, "Title": "Asset Management Sample", "Sum": 1020000.0, "Budget":0
}, {
"Year": 2019,
"Title": "Monday test 2",
"Sum": 2546658.0,
"Budget":100
}, {
"Year": 2020,
"Title": "Asset Management Sample",
"Sum": 1020000.0,
"Budget":1000
}, {
"Year": 2020,
"Title": "Monday test 2",
"Sum": 3472000.0,
"Budget":100
}, {
"Year": 2021,
"Title": "Asset Management Sample",
"Sum": 1020000.0,
"Budget":100
}, {
"Year": 2021,
"Title": "Monday test 2",
"Sum": 2452000.0,
"Budget":100
}]
That I need to change to:
[{
"Year": 2019,
"Asset Management Sample": 1020000.0,
"Monday test": 2546658.0
}, {
"Year": 2020,
"Asset Management Sample": 1020000.0,
"Monday test 2": 3472000.0
}, {
"Year": 2021,
"Asset Management Sample": 1020000.0,
"Monday test 2": 2452000.0
}]
With help from earlier posters I have used .reduce (slightly modified from below) to generate this:
var res = arr.reduce(function(acc, curr) {
acc[curr.Year] = acc[curr.Year];
acc[curr.Year] = acc[curr.Year] || { Year: curr.Year } ;
acc[curr.Year][curr.Title] = curr.Sum;
return acc;
I need to expand this to include a sum of all the budget values for each year (there should be a single budget value per year). I added the following line in before the return:
acc[curr.Year][curr.Budget] = curr[curr.Budget] || { Budget: curr.Budget } ;
It is adding individual entries for each Budget value. How do I sum the Budget values and return it without affecting the other returned array?