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}

解决方法:

您可以将数组reduce转换为Map,如果地图上已经存在ID,则可以对价格求和.然后将spreadMap.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);
上一篇:Lodash-一个一致性、模块化、高性能的 JavaScript 实用工具库介绍


下一篇:javascript-比较对象数组和对象的所有值