gpt4 book ai didi

node.js - 使用lodash中的键值合并对象数组?

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:40 24 4
gpt4 key购买 nike

我正在使用 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] ] } ]

最佳答案

这对你有用:

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来自在你的最终数组上:

_.uniq(byUser, "to");

/*
[ { to: 'foo@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo1@bar.com', submittedSubs: [ [Object] ] },
{ to: 'foo2@bar.com', submittedSubs: [ [Object], [Object], [Object] ] } ]
*/

关于node.js - 使用lodash中的键值合并对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31549960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com