给定以下对象数组:
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/