node.js - Merge an array of objects using key value in lodash? -


i'm using node.js , lodash.

i have data this:

[    {      to: [ 'foo@bar.com', 'foo1@bar.com' ],     submittedsubs: [ [object] ]    },   {      to: [ 'foo@bar.com', 'foo2@bar.com' ],     submittedsubs: [ [object], [object], [object] ]    }  ] 

i'd turn data it's "sorted" to

[    {      to: 'foo@bar.com',      submittedsubs: [ [object],[object], [object], [object] ]    },   {      to: 'foo1@bar.com',      submittedsubs: [ [object] ]    },   {      to: 'foo2@bar.com',     submittedsubs: [ [object], [object], [object] ]    } ] 

how can this?

i've tried this:

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)); 

but gives me this:

[ { 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] ] } ] 

this'll work you:

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] ] } ] */ 

i stand should achievable using callback feature of _.uniq couldn't work way needed to.

you should able use _.uniq on final array:

_.uniq(byuser, "to");  /* [ { to: 'foo@bar.com', submittedsubs: [ [object] ] }, { to: 'foo1@bar.com', submittedsubs: [ [object] ] }, { to: 'foo2@bar.com', submittedsubs: [ [object], [object], [object] ] } ] */ 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -