javascript - 按值合并数组中的对象并获取每个对象的计数

标签 javascript arrays merge count lodash

给定以下对象数组:

myArray = [
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
  },
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
  },
  {
    item: 'Item 3',
    material: 'Material3',
    type: 'support'
  },
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
  },
  {
    item: 'Item 3',
    material: 'Material3',
    type: 'support'
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
  }
]

我需要将这些按 item 值与计数结合起来,以便我得到一个如下所示的数组:

var myResultArray = [
  {
    item: 'Item 1',
    material: 'Material1',
    type: 'head'
    count: 4
  },
  {
    item: 'Item 2',
    material: 'Material2',
    type: 'shell'
    count: 3
  },
  {
    item: 'Item 3',
    material: 'Material3',
    type: 'support'
    count: 2
  },
]

最简单的方法是什么?我偏爱 Lodash,但我对其他选择持开放态度。使用 _.groupBy() 我可以将所有内容与项目组合在一起作为对象键:

var myGrouped = _.groupBy(myArray, 'item');

但这只会让我走到那一步。在这里搜索,我看到了很多 _.reduce() 的用法(或者只是普通的 .reduce())或 _.map(),但在这种情况下我无法确切地了解如何使用它们。如果我尝试像这样使用 _.groupBy()_.map() 链接

var myGrouped = _(myArray).groupBy('item').map(function(item) {
                  // do stuff here
                });

执行甚至没有到达我的 map 函数,所以我不确定我做错了什么。

谢谢。

最佳答案

_.groupBy_.map 链接是最简单的解决方案。 _.map 的正确回调函数是:

function (items) {
  items[0].count = items.length;
  return items[0];
}

或者您可以使用 ES6 箭头函数进一步压缩它。

const myArray = [{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 2","material":"Material2","type":"shell"},{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 2","material":"Material2","type":"shell"},{"item":"Item 3","material":"Material3","type":"support"},{"item":"Item 1","material":"Material1","type":"head"},{"item":"Item 3","material":"Material3","type":"support"},{"item":"Item 2","material":"Material2","type":"shell"}];

const myResultArray =
  _(myArray)
    .groupBy('item')
    .map(items => (items[0].count = items.length, items[0]))
    .value();

console.log(myResultArray);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

关于javascript - 按值合并数组中的对象并获取每个对象的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728299/

相关文章:

javascript - 将 Action 链接在一起形成 NgRx (Angular) 的效果

javascript - 用于提升 React 性能的 Immutable.js 替代方案

ios - 迭代数组时 Swift 无限循环

c++ - 指向堆上数组的指针的地址

Java 计数器即将耗尽

r - 如何合并 column1 是 column2 的子字符串的数据框

git - 在 master 之前恢复与旧分支的 merge

javascript - 从纬度/经度坐标获取一个单词

svn - SVN 中不可修复的混合修订工作副本

javascript - 将变量值传递回 Controller 的angularJs方法是什么