集团&使用lodash汇总行

时间:2018-03-05 04:56:35

标签: javascript lodash

我正在使用以下内容处理购物车中的行。我想要对行进行分组并对分组中的值求和。我根本无法得到这笔钱,我希望能得到一些帮助。

提前致谢

- 数据

var cart: [
      {
        id: 2,
        title: 'Batteries',
        description: 'AAA size batteries',
        price: 10.99
      },
      {
        id: 1,
        title: 'Beacons',
        description: 'Bluetooth long life beacons',
        price: 30.00
      },
      {
        id: 1,
        title: 'Beacons',
        description: 'Bluetooth long life beacons',
        price: 30.00
      }
    ]

- 代码

 const groupedResult = _(cart)
    .groupBy('price')
    .map(function(items, price, title) {
      return {
        title: _.map(items, 'title'),
        description: _.map(items, 'description'),
         price: _.sum(price, 'price'),
      };
    }).value()

- 当前输出

    {title: Array(2), description: Array(2), price: "30"}
    {title: Array(1), description: Array(1), price: "10.99"}

- 预期产出

   {title: 'Beacons', description: 'Bluetooth long life beacons', price: '30.00', total: '60.00', quantity: 2}
   {title: 'Batteries', description: 'AAA size batteries', price: '10.99', total: '10.99', quantity: 1}

2 个答案:

答案 0 :(得分:2)

您可以将数组reduce变为Map,并在地图上已存在id时汇总价格。然后spread Map.values()返回数组:



const cart = [{"id":2,"title":"Batteries","description":"AAA size batteries","price":10.99},{"id":1,"title":"Beacons","description":"Bluetooth long life beacons","price":30},{"id":1,"title":"Beacons","description":"Bluetooth long life beacons","price":30}];
    
const result = [...cart.reduce((r, o) => {
  // add a new item to the map, and set price and quantity to 0
  r.has(o.id) || r.set(o.id, Object.assign({}, o, { price: 0, quantity: 0 }));
  
  // get current item;
  const item = r.get(o.id);
  
  // add current price to item
  item.price += o.price;
  
  // increment quantity
  item.quantity++;

  return r;
}, new Map()).values()]; // spread the values iterator back to array

console.log(result);




答案 1 :(得分:2)

groupBy返回一个对象而不是数组,但是一旦使用Object.values打开结果,就可以使用Array.from()获取此值。因此,假设titledescriptionprice具有相同id的相同值,则应该有效:

 const groupedResult = Object.values(Array.from(_(cart)
 .groupBy('id')))
 .map(x => ({
   title: x[0].title,
   description: x[0].description,
   price: x[0].price,
   quantity: x.length,
   total: _.sumBy(x, x => x.price)
 }));

注意:sumBy仅适用于lodash 4.0.0及更高版本。