我正在使用node.js和lodash。
我有这样的数据:
[
{
to: [ 'foo@bar.com', 'foo1@bar.com' ],
submittedSubs: [ [Object] ]
},
{
to: [ 'foo@bar.com', 'foo2@bar.com' ],
submittedSubs: [ [Object], [Object], [Object] ]
}
]
我希望将其转换为这样的数据,在这些数据中排序""排序"按to
[
{
to: 'foo@bar.com',
submittedSubs: [ [Object],[Object], [Object], [Object] ]
},
{
to: 'foo1@bar.com',
submittedSubs: [ [Object] ]
},
{
to: 'foo2@bar.com',
submittedSubs: [ [Object], [Object], [Object] ]
}
]
我该怎么做?
我试过这个:
spam[0].to.push('foo@bar.com');
spam[0].to.push('foo1@bar.com');
spam[1].to.push('foo@bar.com');
spam[1].to.push('foo2@bar.com');
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: 'foo@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo1@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo@bar.com', submittedSubs: [ [Object], [Object], [Object] ] },
{ to: 'foo2@bar.com', submittedSubs: [ [Object], [Object], [Object] ] } ]
答案 0 :(得分:1)
这对你有用:
var unique = {};
byUser.forEach(function(user) {
unique[user.to] = unique[user.to] || [];
unique[user.to] = unique[user.to].concat(user.submittedSubs);
});
unique = Object.keys(unique).map(function (key, i) {
return {to: key, submittedSubs: unique[key]};
});
/*
[ { to: 'foo@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo1@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo2@bar.com', submittedSubs: [ [Object], [Object], [Object], [Object] ] } ]
*/
我支持这应该可以使用_.uniq
的回调功能实现,但我无法按照您需要的方式使用它。
_.uniq(byUser, "to");
/*
[ { to: 'foo@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo1@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo2@bar.com', submittedSubs: [ [Object], [Object], [Object] ] } ]
*/
答案 1 :(得分:1)
我想有一些不错的lodash
设施可以缩短这一点,但这里有一个vanilla-js解决方案:
var data = [
{
to: [ 'foo@bar.com', 'foo1@bar.com' ],
submittedSubs: [{ id: 'sub1' }]
},
{
to: [ 'foo@bar.com', 'foo2@bar.com' ],
submittedSubs: [{ id: 'sub2' }, { id: 'sub3' }, { id: 'sub4' }]
}
];
var emailSubsMap = data.reduce(function(result, record) {
record.to.forEach(function(email) {
result[email] = (result[email] || [])
.concat(record.submittedSubs);
});
return result;
}, {});
var formatted = Object.keys(emailSubsMap).map(function(email) {
return { to: email, submittedSubs: emailSubsMap[email] };
}).sort(function(a, b) {
return a.to <= b.to ? -1 : 1;
});
console.log(JSON.stringify(formatted));
(格式化)控制台输出:
[
{
"to": "foo1@bar.com",
"submittedSubs": [
{ "id": "sub1" }
]
},
{
"to": "foo2@bar.com",
"submittedSubs": [
{ "id": "sub2" },
{ "id": "sub3" },
{ "id": "sub4" }
]
},
{
"to": "foo@bar.com",
"submittedSubs": [
{ "id": "sub1" },
{ "id": "sub2" },
{ "id": "sub3" },
{ "id": "sub4" }
]
}
]
请注意,我模拟了submittedSubs
对象的外观,仅用于测试目的。
关于排序的一些注意事项:
['foo@bar.com', 'foo2@bar.com', 'foo1@bar.com'].sort() --> ['foo1@bar.com','foo2@bar.com','foo@bar.com']
,如果您真的希望foo@bar.com
在foo1@bar.com
之前到来,则需要更详细地定义排序条件。