javascript对象分组依据具有不同的属性

时间:2018-12-12 15:22:25

标签: javascript object properties reduce

我的问题很简单

我的输入是

[ 
 { department_id: '28', linear_meter: 6 },
 { department_id: '56', linear_meter: 19 },
 { department_id: '28', square_meters: 20.28 },
 { department_id: '56', square_meters: 18.28827 } 
]

我想要这样的东西:

      [
       {
         "department_id": 28,
         "linear_meters": 6,
         "square_meters": 20.28
        },
       {
         "department_id": 56,
         "linear_meters": 19,
         "square_meters": 18.28827
        },
       ]

我尝试过,但是结果不完全是我想要的

var result = arr.reduce(function (res, obj) {
            if (!(obj.department_id in res))
                res.__array.push(res[obj.department_id] = obj);
            else {
                res[obj.department_id].linear_meter += obj.linear_meter;
                res[obj.department_id].square_meters += obj.square_meters;
            }
            return res;
        }, {__array: []}).__array;

但输出是:

[ { department_id: '28', 
    linear_meter: NaN, 
    square_meters: NaN },
  { department_id: '56', 
    linear_meter: NaN, 
    square_meters: NaN } ]

有人有主意吗? 我在+ =

之前测试
  typeof res[obj.department_id].square_meters !== "undefined"

但没有任何变化...

2 个答案:

答案 0 :(得分:0)

对象可能没有该项目,因此您要为未定义添加数字。最简单的方法是使用Object.assign()复制属性。

var arr = [{
    department_id: '28',
    linear_meter: 6
  },
  {
    department_id: '56',
    linear_meter: 19
  },
  {
    department_id: '28',
    square_meters: 20.28
  },
  {
    department_id: '56',
    square_meters: 18.28827
  }
];

var result = arr.reduce(function(res, obj) {
  if (!(obj.department_id in res))
    res.__array.push(res[obj.department_id] = obj);
  else {
    Object.assign(res[obj.department_id], obj)

  }
  return res;
}, {
  __array: []
}).__array;

console.log(result)

答案 1 :(得分:0)

使用department_id合并属性,然后使用Object.assign()返回最终数组的另一种方法,简化为以Object.values作为键的对象

const data = [ 
 { department_id: '28', linear_meter: 6 },
 { department_id: '56', linear_meter: 19 },
 { department_id: '28', square_meters: 20.28 },
 { department_id: '56', square_meters: 18.28827 } 
]


const res = Object.values(
  data.reduce(function(a, c) {
    const id = c.department_id;
    a[id] = a[id] || {}
    Object.assign(a[id], c)
    return a;
  }, {})
)

console.log(res)