Hemant
Hemant

Reputation: 170

get sum of JSON array values

I tried to get the sum of this JSON array values. But I don't know the right way to to do this.

var taxes = [ {"1": 11}, {"2": 33} ];

result = 44;

Upvotes: 0

Views: 4006

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You can try with Array.prototype.map() and Array.prototype.reduce()

var taxes = [{"1":11},{"2":33}];
const result = taxes.map(a=>Object.values(a)).reduce((a,b)=>parseInt(a)+parseInt(b))
console.log("result = "+result);

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39322

You can use .reduce() to calculate sum like this:

let taxes = [{"1":11}, {"2":33}];

let result = taxes.reduce((a, c) => a + c[Object.keys(c)], 0);

console.log(result);

In case your objects are having consecutive numbers as properties you can use a simpler approach like:

let taxes = [{"1":11}, {"2":33}];

let result = taxes.reduce((a, c, i) => a + c[i + 1], 0);

console.log(result);

Upvotes: 1

Anthony
Anthony

Reputation: 6482

If each object in the array only has 1 key/value pair, this will work regardless if the keys are sequential:

const result = taxes.reduce((a, b) => a += Object.values(b)[0], 0);

Upvotes: 0

Related Questions