ES6 GroupBy 2或更多

时间:2018-09-05 09:53:56

标签: javascript ecmascript-6

我有一个类似于SQL Group By的ES6代码。

在这里,将具有相同material_no的项目分组,并求和。

let data = [
  { material_no: '1001', material_name: 'Material 1', qty: 100, date: 'jan' },
  { material_no: '1001', material_name: 'Material 1', qty: 50, date: 'feb' },
  { material_no: '1002', material_name: 'Material 2', qty: 44, date: 'mar' },
  { material_no: '1003', material_name: 'Material 3', qty: 125, date: 'apr' },
  { material_no: '1002', material_name: 'Material 2', qty: 59, date: 'mar' },
  { material_no: '1004', material_name: 'Material 4', qty: 999, date: 'may' },
  { material_no: '1005', material_name: 'Material 5', qty: 80, date: 'jun' },
  { material_no: '1005', material_name: 'Material 5', qty: 66, date: 'jun' }
]

const sums = [
  ...data.reduce(
    (map, item) => {
      const { material_no: key, qty } = item;
      const prev = map.get(key);
      
      if(prev) {
        prev.qty += qty
      } else {
        map.set(key, Object.assign({}, item))
      }
      
      return map
    },
    new Map()
  ).values()
]

console.log(sums)

应该将“日期”添加到分组依据逻辑中,

我似乎无法弄清楚该怎么办,因为代码仅在map.get(key)中使用material_no作为键进行比较。如何同时使用material_no和date。

2 个答案:

答案 0 :(得分:1)

您可以使用字符串键,该字符串键是material_nodate的串联。

const { material_no, date, qty } = item;
const key = `${material_no}:${date}`;

答案 1 :(得分:0)

let data = [
  { material_no: '1001', material_name: 'Material 1', qty: 100, date: 'jan' },
  { material_no: '1001', material_name: 'Material 1', qty: 50, date: 'feb' },
  { material_no: '1002', material_name: 'Material 2', qty: 44, date: 'mar' },
  { material_no: '1003', material_name: 'Material 3', qty: 125, date: 'apr' },
  { material_no: '1002', material_name: 'Material 2', qty: 59, date: 'mar' },
  { material_no: '1004', material_name: 'Material 4', qty: 999, date: 'may' },
  { material_no: '1005', material_name: 'Material 5', qty: 80, date: 'jun' },
  { material_no: '1005', material_name: 'Material 5', qty: 66, date: 'jun' }
];


var map = {};

data.filter(function(item) {
  if(map[item.material_no + "__" + item.date]) {
    map[item.material_no + "__" + item.date]["qty"] += item.qty;
  } else {
    map[item.material_no + "__" + item.date] = {
      material_name: item.material_name,
      qty: item.qty,
      material_no: item.material_no,
      date: item.date
    };
  }
});


console.log(Object.values(map));