axon axon - 6 months ago 8
Javascript Question

How to union/group array of objects by same values and by some property?

I have some array:



[
{
billable: 1,
source: "Facebook",
providerAccountId: 5,
message_id: "5bb1a457"
},
{
billable: 1,
source: "Facebook",
providerAccountId: 5,
message_id: "6bb3G465"
},
{
destination: "8801856472841"
message_id: "5bb1a457"
}
]

//after union, i need to get result:

[
{
billable: 1,
source: "Facebook",
providerAccountId: 5,
message_id: "5bb1a457"
destination: "8801856472841"
},
{
billable: 1,
source: "Facebook",
providerAccountId: 5,
message_id: "6bb3G465"
}
]





Help please, myabe is it possable to group or to union by property with unique value. just to join all objects which have same values by specified peoperty and missing properties add into joined objects

Answer

you can map it by the key you want to check and eventually merge it:

var d = [
  {
    billable: 1,
    source: "Facebook",
    providerAccountId: 5,
    message_id: "5bb1a457"
  },
  {
    billable: 1,
    source: "Facebook",
    providerAccountId: 5,
    message_id: "6bb3G465"
  },
  {
    destination: "8801856472841",
    message_id: "5bb1a457"
  }
];

var res =  d.reduce((ac,x) => {
   if (ac[x.message_id])
     Object.assign(ac[x.message_id],x); //if you want to preserve original use a new object as target
   else
     ac[x.message_id]=x;
   return ac;
 },{})

// and then you can map it back to array
var res2 = Object.keys(res).map(x => res[x]) 

console.log(res)
console.log(res2)