在react.js中添加列值

时间:2018-10-23 01:24:11

标签: javascript

添加所有列值的最佳方法是什么?
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"
  }
]

我正在从服务器中获取数据,我想添加所有值并将其显示在控制台中。 例如,在控制台中const value = 3 + 5 + 5 = 13。

1 个答案:

答案 0 :(得分:6)

那与reactjs无关,

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