Reputation: 71
I need a little help to reorganize this array of objects:
[
{employee: "PLUTO", "MON1": 6},
{employee: "PLUTO", "TUE2": 6},
//etc..
{employee: "DONALD", "MON1":7},
{employee: "DONALD", "TUE2":7},
//etc...
]
I need to get a result like:
[
{employee: "PLUTO", "MON1":6, "TUE2":6, "etc...."},
{employee: "DONALD", "MON1":7, "TUE2",7", "etc..."}
]
I'm able to get only one object with reduce function to create a new object:
var test = myArr.reduce((acc, it) => Object.assign(acc, it), {});
console.log(test);
[{employee: "DONALD", "MON1":7, "TUE2":7, "etc..."}] <--get only the last employee
Thank you in advance
Upvotes: 0
Views: 113
Reputation: 5308
You can make use reduce to group the data by name and take Object.values
in the last:
const arr = [
{employee: "PLUTO", "MON1": 6},
{employee: "PLUTO", "TUE2": 6},
//etc..
{employee: "DONALD", "MON1":7},
{employee: "DONALD", "TUE2":7},
//etc...
];
const result = arr.reduce((a,e)=>(a[e.employee]={...(a[e.employee] || {}), ...e}, a),{});
console.log(Object.values(result));
Upvotes: 3
Reputation: 372
This should do it.
myArr.reduce((acc,it)=>{
const index = acc.map(i=>i.employee).indexOf(it.employee);
if(index === -1)
acc.push(it);
else
Object.assign(acc[index],it);
return acc;
},[])
Upvotes: 2