我正在使用node.js和lodash。使用lodash中的键值合并一个对象数组?
我有这样的数据:
[
{
to: [ '[email protected]', '[email protected]' ],
submittedSubs: [ [Object] ]
},
{
to: [ '[email protected]', '[email protected]' ],
submittedSubs: [ [Object], [Object], [Object] ]
}
]
我希望把它变成在那里它是由to
[
{
to: '[email protected]',
submittedSubs: [ [Object],[Object], [Object], [Object] ]
},
{
to: '[email protected]',
submittedSubs: [ [Object] ]
},
{
to: '[email protected]',
submittedSubs: [ [Object], [Object], [Object] ]
}
]
我该怎么做“分类”像这样的数据?
我已经试过这样:
spam[0].to.push('[email protected]');
spam[0].to.push('[email protected]');
spam[1].to.push('[email protected]');
spam[1].to.push('[email protected]');
console.log('data is',spam);
var byUser=[];
_.each(spam, function(data){
_.each(data.to,function(addr){
byUser.push({to:addr,submittedSubs:data.submittedSubs});
});
});
console.log('attempt',_.merge(byUser));
但是,这给了我这样的:
[ { to: '[email protected]', submittedSubs: [ [Object] ] },
{ to: '[email protected]', submittedSubs: [ [Object] ] },
{ to: '[email protected]', submittedSubs: [ [Object], [Object], [Object] ] },
{ to: '[email protected]', submittedSubs: [ [Object], [Object], [Object] ] } ]
看起来最简单的方法是以电子邮件地址为关键字创建一个对象,其值为一个对象数组。然后可以将它转换回数组并在'to'字段中排序。 –