本文介绍了使用LoDash合并包含相同键/值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从初始数组对LoDash进行一些操作后,我得到以下结果:

After doing some operations with LoDash from an initial array, I end up with the following:

[
  {number:3, product:'apple'},
  {number:2, product:'apple'},
  {number:4, product:'pear'}
]

我如何操纵它最终导致:

How could I manipulate it to end up with:

[
  {number:5, product:'apple'},
  {number:4, product:'pear'}
]

这是原始代码,以防万一:

This is the original code, just in case:

$scope.data = [
  {
    date:'date',
    products: [
      {
        number: 3,
        product: 'Apple'
      },
      {
        number: 4,
        product: 'Pear'
      }
    ]
  },
  {
    date:'date',
    products: [
      {
        number: 2,
        product: 'Apple'
      }
    ]
  }
]


const grouped = _.groupBy($scope.data, function(el){
  return moment(el.date).format('dddd, D [de] MMMM');
});

const result = _.map(grouped, (value, date) => ({
    date: date,
    products: _.flatMap(value, el => el.products)
}));

推荐答案

您必须按产品添加单独的分组,与按日期分组非常相似

You have to add separate grouping by products, very similar as grouping by date

// Function for grouping unique products with sum of units
function sumProductsUnits(products) {
    var productGroups = _.groupBy(products, productObj => productObj.product);

    return _.map(productGroups, (productGroup, productName) => ({
        product: productName,
        units: productGroup.reduce((sum, val) => sum + val.number, 0)
    }))
}

用法如下:

const result = _.map(grouped, (value, date) => ({
    date: date,
    products: sumProductsUnits(
        _.flatMap(value, el => el.products)
    )
}));


结果:


Result:

[
   {
      "date":"date",
      "products":[
         {
            "product":"Apple",
            "units":5
         },
         {
            "product":"Pear",
            "units":4
         }
      ]
   }
]

这篇关于使用LoDash合并包含相同键/值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:01