根据属性值合并数组中的对象

时间:2018-06-06 14:37:56

标签: javascript ecmascript-6

我的JS应用程序中有一个对象数组,其中包含日期名称,日期和一些项目:

const records = [
  { name: 'Carpat', date: '01/06/18', items: 12 },
  { name: 'Carpat', date: '01/06/18', items: 34 },
  { name: 'Carpat', date: '02/06/18', items: 13 },
  { name: 'Carpat', date: '02/06/18', items: 15 },
  { name: 'Carpat', date: '03/06/18', items: 55 },
  { name: 'Carpat', date: '04/06/18', items: 66 },
]

我想减少这个数组,以便具有相同日期的对象合并为一个,而新的items属性将是合并对象的此属性之和的结果。结果应该是这样的:

const records = [
      { name: 'Carpat', date: '01/06/18', items: 46 },
      { name: 'Carpat', date: '02/06/18', items: 28 },
      { name: 'Carpat', date: '03/06/18', items: 55 },
      { name: 'Carpat', date: '04/06/18', items: 66 },
    ]

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

只需使用日期哈希表并过滤掉欺骗行为:

const hash = {};

const result = records.filter(el => {
  if(hash[el.date]) {
    hash[el.date].items += el.items;
    return false;
  } else {
    hash[el.date] = el;
    return true;
  }
});

直播示例:



const records = [
  { name: 'Carpat', date: '01/06/18', items: 12 },
  { name: 'Carpat', date: '01/06/18', items: 34 },
  { name: 'Carpat', date: '02/06/18', items: 13 },
  { name: 'Carpat', date: '02/06/18', items: 15 },
  { name: 'Carpat', date: '03/06/18', items: 55 },
  { name: 'Carpat', date: '04/06/18', items: 66 },
];

const hash = {};

const result = records.filter(el => {
  if(hash[el.date]) {
    hash[el.date].items += el.items;
    return false;
  } else {
    hash[el.date] = el;
    return true;
  }
});

console.log(result);

.as-console-wrapper {
  max-height: 100% !important;
}