我需要你的帮助...... 我得到了一个像这样的对象数组:
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这样做会很棒!
感谢您的帮助!
答案 0 :(得分:2)
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
答案 1 :(得分:1)
这是一个普通Javascript中的提议,带有一个临时对象,用于引用结果数组。
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' }],
grouped = function (array) {
var r = [], o = {};
array.forEach(function (a) {
if (!o[a.user]) {
o[a.user] = { title: a.title, user: a.user, events: [] };
r.push(o[a.user]);
}
o[a.user].events.push({ price: a.price, location: a.location });
});
return r;
}(arr);
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
答案 2 :(得分:1)
Lodash回答:
function remap(arr) {
var out = _.reduce(arr, function(p, c) {
var key = [c.user, c.title].join('|');
p[key] = p[key] || { title: c.title, user: c.user, events: [] };
p[key].events.push({ price: c.price, location: c.location });
return p;
}, {});
return _.map(_.keys(out), function(el) {
return out[el];
});
}
remap(arr);