-1

I have an array of objects:

[ 
   {department: 'IT', employee: 'Niall', position: 'UI developer'},
   {department: 'FINANCE', employee: 'Jimmy', position: 'Financial Analyst'},
   {department: 'IT', employee: 'John', position: 'web designer'},
   {department: 'FINANCE', employee: 'William', position: 'Consultant'},
   {department: 'HEALTH', employee: 'Andy', position: 'doctor'}
]

I want to merge the objects by department and create a new object with two properties: the key by which we did the merge, and a 'details' property which is an array of objects of all the other properties by employee. The desired output is :

[
  {
    'department' : 'IT',
    'details': [ {'employee': 'Niall', 'position': 'UI developer'},
                 {'employee': 'John', 'position': 'web designer'}]
  },
  {
    'department' : 'FINANCE',
    'details': [ {'employee': 'Jimmy', 'position': 'Financial Analyst'},
                 {'employee': 'William', 'position': 'Consultant'}]
  },
  {
    'department' : 'FINANCE',
    'details': [ {'employee': 'Andy', 'position': 'doctor'}]
  }
]

1 Answers1

0

const data = [{"department":"IT","employee":"Niall","position":"UI developer"},{"department":"FINANCE","employee":"Jimmy","position":"Financial Analyst"},{"department":"IT","employee":"John","position":"web designer"},{"department":"FINANCE","employee":"William","position":"Consultant"},{"department":"HEALTH","employee":"Andy","position":"doctor"}]

console.log(Object.values(data.reduce((a,{department:d, ...o})=>
  ((((a[d]??={department:d}).details??=[]).push(o)),a),{})))
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27