【问题标题】:Removing duplicate items from an object and getting the sum of a key if there is a duplicate从对象中删除重复项并在存在重复项时获取键的总和
【发布时间】:2016-12-16 11:49:57
【问题描述】:

我有一个对象数组。

var $arr = [
    {'product': 1, 'quantity': 4, 'service': 'AC'},
    {'product': 2, 'quantity': 5, 'service': 'TV'},
    {'product': 1, 'quantity': 3, 'service': 'AC'}
];

使用此数组,我需要删除“产品”和“服务”键都匹配的任何对象。我需要做的另一件事是,如果两个或多个对象之间存在匹配,则取每个对象的“数量”值并计算总和。

我一直在使用 lodash 来尝试实现这一点。虽然我觉得我离找到解决方案并不太远,但我似乎无法确定问题的最后一部分并将“数量”值相加(如果有匹配项)。

console.log(_.uniqBy($arr, function(v) {
    return v.product === 1;
}));

这有可能吗,还是我需要重新考虑解决这个问题的方法。此外,我因无法使用 ES6 而受到责备,这是一种耻辱。

感谢您的帮助。

【问题讨论】:

  • 你需要_.mergeWith

标签: javascript jquery lodash


【解决方案1】:

使用_.groupBy()将具有相同产品和服务值的对象收集到数组中,然后使用_.mergeWith()将每个数组合并为一个。

该示例使用 ES6 箭头函数和数组展开:

var $arr = [{"product":1,"quantity":4,"service":"AC"},{"product":2,"quantity":5,"service":"TV"},{"product":1,"quantity":3,"service":"AC"}];

var result = _($arr)
  // group the object by product and service
  .groupBy(({ product, service }) => product + service)
   // merge each group, and if the key is quantity add the numbers
  .map((g) => _.mergeWith(...g, (o, s, k) => k === 'quantity' ? o + s : o))
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2021-12-23
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多