按相似数据分组,但保留键和值javascript

时间:2018-11-12 04:05:46

标签: javascript json

在工作期间,我对此任务有疑问,这是我的数据:

var order = [
      {area: "RFCC",ru: "R401",tot: 3,unit: "OFFSITE"},
      {area: "RFCC",ru: "R401",tot: 1,unit: "RCU"}];

我希望结果应该像这样:

var order = [
    {area:["RFCC","RFCC"],ru:["R401","R401"],tot:[4],unit:["OFFSITE","RCU"]}]

有人知道解决方案吗?预先感谢。

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式使用Array#reduce()实现这一目标:

var order = [
      {area: "RFCC",ru: "R401",tot: 3,unit: "OFFSITE"},
      {area: "RFCC",ru: "R401",tot: 1,unit: "RCU"}
];

var result = order.reduce((result, item) => {
  
  const { area, ru, tot, unit } = result[0]
   
  area.push( item.area );
  ru.push( item.ru );
  unit.push( item.unit );
  tot[0] = parseInt(tot[0]) + parseInt(item.tot);
  
  return result

}, [{ area : [], ru : [], tot: [ 0 ], unit : [] }])

console.log(result);

答案 1 :(得分:1)

您可以使用“ for..of”遍历数组对象

var order = [
      {area: "RFCC",ru: "R401",tot: 3,unit: "OFFSITE"},
      {area: "RFCC",ru: "R401",tot: 1,unit: "RCU"}
];
  
var result = {}

for(let obj of order) {
  for(let [key, value] of Object.entries(obj)) {
    
    typeof value == "string" && (
      result[key] = result[key] ? result[key].concat(value) : [value]
    )
    
    typeof value == "number" && (
      result[key] = result[key] ? [result[key][0] + value] : [value]
    )
  }
}

console.log(result)