Ajax JSON SUMIF数组包含一个特定的单词

时间:2018-03-22 11:09:47

标签: javascript json

在jQuery中有没有办法我可以添加包含SUM的所有JSON对象的BC作为客户端属性的值?我无法找到解决方案,我试过这个:

[
  {
    client: "BC",
    users: "PHIL",
    levels: "EAST",
    SUM: "32,600.00"
  },
  {
    client: "BC",
    users: "PHIL",
    levels: "EAST",
    SUM: "12,600.00"
  },
  {
    client: "AQ",
    users: "PHIL",
    levels: "WEST",
    SUM: "20,600.00"
  },
  {
    client: "AQ",
    users: "PHIL",
    levels: "WEST",
    SUM: "16,600.00"
  }
]

1 个答案:

答案 0 :(得分:1)

您可以按如下方式使用filter,map和reduce:

var items = [{"client": "BC", "users": "PHIL", "levels": "EAST", "SUM":"32,600.00"},
      {"client": "BC", "users": "PHIL", "levels": "EAST", "SUM": "12,600.00"},
      {"client": "AQ", "users": "PHIL", "levels": "WEST", "SUM": "20,600.00"},          
      {"client": "AQ", "users": "PHIL", "levels": "WEST", "SUM": "16,600.00"}];

var sum = items.filter(item => {
    // get only ones with client property equals to 'BC'
    return item.client === "BC";
  }).map(item => {
    // parse SUM property values removing the commas and convert them to int
    return parseInt(item.SUM.replace(/,/g, ""));
  }).reduce((a, b) => {
    // sum 
    return a + b;
  }, 0);
    
console.log(sum);