我需要你的帮助... 我得到了一个看起来像这样的对象数组:
var arr = [{
title: 'My title',
user: 1,
price: 22,
location: 'Berlin'
},{
title: 'My title',
user: 1,
price: 18,
location: 'Cologne'
},{
title: 'My title',
user: 1,
price: 26,
location: 'Hamburg'
},{
title: 'Other Title',
user: 2,
price: 26,
location: 'Frankfurt'
},{
title: 'Other Title',
user: 2,
price: 28,
location: 'Munich'
},];
现在我想构建一个新的对象数组,如下所示:
var result = [{
title: 'My title',
user: 1,
events: [
{
price: 22,
location: 'Berlin'
}, {
price: 18,
location: 'Cologne'
}, {
price: 26,
location: 'Hamburg'
}
]
},{
title: 'Other Title',
user: 2,
events: [
{
price: 28,
location: 'Munich'
},{
price: 26,
location: 'Frankfurt'
}
]
}];
我需要按多个值对对象进行分组,就像在我的示例中按用户和标题进行分组,并将它们的唯一数据添加到新字段中。
如果有人能告诉我如何使用 lodash 做到这一点,那就太棒了!
感谢您的帮助!
最佳答案
arr.reduce(function (hash, item) {
var key = item.title + item.user;
var obj = hash[key] || {};
obj.title = item.title;
obj.user = item.user;
obj.events = obj.events || [];
obj.events.push({
price: item.price,
location: item.location
});
hash[key] = obj;
return hash;
}, {});
var result = [];
for (var key in arr) {
result.push(arr[key]);
}
console.log(result); // the result array
关于javascript - 使用包含来自具有特定键的重复值的对象数组的唯一数据的数组构建新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35917353/