使用LoDash合并包含相同键/值的对象

时间:2017-03-05 17:43:12

标签: angularjs arrays lodash

在从初始数组中使用LoDash执行某些操作后,我最终得到以下结果:

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

我怎么能操纵它最终:

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

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

$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)
}));

1 个答案:

答案 0 :(得分:4)

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

UPDATE authors SET published_articles = 
(
SELECT COUNT(*) FROM articles 
WHERE articles.author_id=authors.author_id AND articles.status='published' 
GROUP BY author_id
)

用法如下:

count(*)

结果:

// 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)
    }))
}