0

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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;
 },[])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.