根据密钥中字符串的出现求和json数组,并将其与字符串及其计数一起存储在单独的json数组中

时间:2019-01-03 10:24:54

标签: jquery json ajax

我有一个包含数据的JSON数组,如下所示:

var teamDetails=[ 
 { "pType" : "Search Engines", "count" : 5},
 { "pType" : "Content Server", "count" : 1},
 { "pType" : "Content Server", "count" : 1},
 { "pType" : "Search Engines", "count" : 1},
 { "pType" : "Business", "count" : 1,},
 { "pType" : "Content Server", "count" : 1},
 { "pType" : "Internet Services", "count" : 1},
 { "pType" : "Search Engines", "count" : 6},
 { "pType" : "Search Engines", "count" : 1} 
];

因此,我需要基于ptype来计算计数,例如Content Server = 3倍,Search Engines = 12倍,依此类推。由于我在Rest Services上工作,因此数据不是静态的,因此它会更改,但是数据的格式是相同的。该代码应该是动态的,以处理ptype数据中的任何更改。

1 个答案:

答案 0 :(得分:1)

您可以使用reduce来解决此问题。这就是它的样子

var data = teamDetails.reduce((prev, curr) => {
  const index = prev.findIndex(a => a.pType === curr.pType)
  if (index !== -1) {
    prev[index].count = prev[index].count + curr.count;
  } else {
  prev.push(curr);
  }
  return prev;
}, [])

var teamDetails = [{
    "pType": "Search Engines",
    "count": 5
  },
  {
    "pType": "Content Server",
    "count": 1
  },
  {
    "pType": "Content Server",
    "count": 1
  },
  {
    "pType": "Search Engines",
    "count": 1
  },
  {
    "pType": "Business",
    "count": 1,
  },
  {
    "pType": "Content Server",
    "count": 1
  },
  {
    "pType": "Internet Services",
    "count": 1
  },
  {
    "pType": "Search Engines",
    "count": 6
  },
  {
    "pType": "Search Engines",
    "count": 1
  }
];

var data = teamDetails.reduce((prev, curr) => {
  const index = prev.findIndex(a => a.pType === curr.pType)
  if (index !== -1) {
    prev[index].count = prev[index].count + curr.count;
  } else {
  prev.push(curr);
  }
  return prev;
}, [])
console.log(data);