4

What is the best approach to add all the columns value?
json

[
  {
    "id": "men",
    "label": "men",
    "value": 3,
    "color": "#468df3"
  },
  {
    "id": "women",
    "label": "women",
    "value": 5,
    "color": "#ba72ff"
  },
  {
    "id": "children",
    "label": "children",
    "value": 5,
    "color": "#a1cfff"
  }
]

I am fetching data from the server I like to add all the values and display it in the console. For example const value = 3+5+5 = 13 in console.

1 Answer 1

6

That's not related to reactjs, simply

let raw = '[{"id": "men","label": "men","value": 3,"color": "#468df3"},{"id": "women","label": "women","value": 5,"color": "#ba72ff"},{"id": "children","label": "children","value": 5,"color": "#a1cfff"}]';

let data = JSON.parse(raw);
let sum_value = data.reduce((sum, current)=>{
    return sum + current.value
}, 0);

console.log(sum_value);

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

2 Comments

you have to initialize the reduce with 0. otherwise you get "[object Object]55" as the result =)

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.