won*_*r95 1 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'
}
]
Run Code Online (Sandbox Code Playgroud)
我需要将这些item
值与count 组合在一起,以便得到一个如下所示的数组:
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
},
]
Run Code Online (Sandbox Code Playgroud)
最简单的方法是什么?我偏爱Lodash,但我对其他选择持开放态度.随着_.groupBy()
我可以搞定一切与该项目作为重点对象组合在一起:
var myGrouped = _.groupBy(myArray, 'item');
Run Code Online (Sandbox Code Playgroud)
但那只能让我分道扬.. 在这里搜索我看到了很多用途_.reduce()
(或者只是简单的.reduce()
)或者_.map()
,但是在这种情况下我无法理解如何使用它们.如果我尝试使用_.groupBy()
链接的使用_.map()
,像这样
var myGrouped = _(myArray).groupBy('item').map(function(item) {
// do stuff here
});
Run Code Online (Sandbox Code Playgroud)
执行甚至没有到我的地图功能,所以我不确定我做错了什么.
谢谢.
_.groupBy
链接_.map
是最简单的解决方案.一个适当的回调函数_.map
将是:
function (items) {
items[0].count = items.length;
return items[0];
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)