0

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;
4
  • That's not JSON, that's a literal. Commented Apr 25, 2018 at 17:00
  • What exactly did you try? Commented Apr 25, 2018 at 17:00
  • Why would you have an array of objects with different keys in each? Commented Apr 25, 2018 at 17:03
  • I'd recommend you start by looking at JS's reduce and then provide what you've tried and what doesn't work. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 25, 2018 at 17:03

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

7 Comments

You're assuming that the property name in each object will always be sequential integers. I'm not sure I would extrapolate that from an example of just two elements.
@Barmar Yes, you are right. But may be objects are having consecutive numbers as properties. OP should clarify this.
I generally ask for such clarification in a comment before posting an answer, or I make the assumption clear in my answer.
@Barmar I've tried to add an alternate approach which is not dependent on any condition and hopefully will work in any similar case.
Can you explain how c[[Object.keys(c)]] works in that example? Why double brackets?
|
0

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.