Reputation: 27
I have 1 object with complete data, and 2 array of keys those are exist in object, how can i get sum of every key of from 2 array.
const data = [{
DateMeasured: "8/30/2018",
AsthmaDiaryReading: "100",
AsthmaDiaryPersonalBest: "100",
Comment: ""
},{
DateMeasured: "8/29/2018",
AsthmaDiaryReading: "200",
AsthmaDiaryPersonalBest: "150",
Comment: ""
},{
DateMeasured: "8/15/2018",
AsthmaDiaryReading: "300",
AsthmaDiaryPersonalBest: "50",
Comment: ""
},{
DateMeasured: "8/6/2018",
AsthmaDiaryReading: "100",
AsthmaDiaryPersonalBest: "200",
Comment: ""
},{
DateMeasured: "9/6/2017",
AsthmaDiaryReading: "500",
AsthmaDiaryPersonalBest: "100",
Comment: ""
}
];
Sum key,
array = [
'AsthmaDiaryReading',
'AsthmaDiaryPersonalBest'
]
Desire sum should be like below:
object = {
AsthmaDiaryReading: "1200" ,
AsthmaDiaryPersonalBest: '600'
}
Upvotes: 0
Views: 36
Reputation: 972
A pure reduce option, albeit not very pretty:
const sumOfKeys = (keys, data) => data.reduce(
(total, entry) =>
keys.reduce(
(acc, k) => ({ ...acc, [k]: (total[k] || 0) + Number(entry[k]) }),
{},
),
{},
);
sumOfKeys(dataKeys, data)
Upvotes: 0
Reputation: 5260
Using reduce
with a for in
loop inside is shorter:
const data = [{
AsthmaDiaryReading: '100',
AsthmaDiaryPersonalBest: '100',
},
{
AsthmaDiaryReading: '200',
AsthmaDiaryPersonalBest: '150',
},
{
AsthmaDiaryReading: '300',
AsthmaDiaryPersonalBest: '50',
},
{
AsthmaDiaryReading: '100',
AsthmaDiaryPersonalBest: '200',
},
{
AsthmaDiaryReading: '500',
AsthmaDiaryPersonalBest: '100',
},
];
var res = data.reduce((acc,c)=>{
for(let a in c){
acc[a] = (acc[a] || 0)+parseInt(c[a]);
}
return acc;
},{})//<-- associative array if you change {} for []
console.log(Object.keys(res))
console.log(res)
Upvotes: 0
Reputation: 23565
You can use of Array.reduce()
const data = [{
AsthmaDiaryReading: '100',
AsthmaDiaryPersonalBest: '100',
},
{
AsthmaDiaryReading: '200',
AsthmaDiaryPersonalBest: '150',
},
{
AsthmaDiaryReading: '300',
AsthmaDiaryPersonalBest: '50',
},
{
AsthmaDiaryReading: '100',
AsthmaDiaryPersonalBest: '200',
},
{
AsthmaDiaryReading: '500',
AsthmaDiaryPersonalBest: '100',
},
];
dataKeys = [
'AsthmaDiaryReading',
'AsthmaDiaryPersonalBest'
];
const initialArray = dataKeys.reduce((tmp, x) => ({
...tmp,
[x]: 0,
}), {});
const ret = data.reduce((tmp, x) => {
Object.keys(tmp).forEach((y) => {
tmp[y] += parseInt(x[y]);
});
return tmp;
}, initialArray);
console.log(ret);
Upvotes: 4