0

I have an array of objects in the following form,

[
    {
        employeeID: 112,
        devicetype: 'Laptop',
        devicename: 'ZENW42NMNC5431',
        deviceID: '123EEB9',
        devicePrimary: 'Yes'
    }
    {
        employeeID: 112,
        devicetype: 'Desktop',
        devicename: 'ZENW42NMNC5432',
        deviceID: '123EEB10',
        devicePrimary: 'No'
    }
    {
        employeeID: 113,
        devicetype: 'Laptop',
        devicename: 'ZENW42NMNC5431',
        deviceID: '123EEB9',
        devicePrimary: 'Yes'
    }
]

I am trying to merge the objects properties based on employeeID. So How do I convert this into following form in javascript.

[{
  employeeID: 112,
  devices: [{
      devicetype: 'Laptop',
      devicename: 'ZENW42NMNC5431',
      deviceID: '123EEB9',
      devicePrimary: 'Yes'
    },
    {
      devicetype: 'Desktop',
      devicename: 'ZENW42NMNC5432',
      deviceID: '123EEB10',
      devicePrimary: 'No'
    }
  ]
} {
  employeeID: 113,
  devices: [{
    devicetype: 'Desktop',
    devicename: 'ZENW42NMNC5433',
    deviceID: '123EEB11',
    devicePrimary: 'No'
  }]
}]
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
FaizanSyed
  • 27
  • 1
  • 5

1 Answers1

1

const initialArray = [
    {
        employeeID: 112,
        devicetype: 'Laptop',
        devicename: 'ZENW42NMNC5431',
        deviceID: '123EEB9',
        devicePrimary: 'Yes'
    },
    {
        employeeID: 112,
        devicetype: 'Desktop',
        devicename: 'ZENW42NMNC5432',
        deviceID: '123EEB10',
        devicePrimary: 'No'
    },
    {
        employeeID: 113,
        devicetype: 'Laptop',
        devicename: 'ZENW42NMNC5431',
        deviceID: '123EEB9',
        devicePrimary: 'Yes'
    }
]

const employees = [];
// Loop trough initial array
for(let i = 0; i < initialArray.length; i++) {
  let employeeId = initialArray[i].employeeID;
  // this will check if id is already in array and skip adding employee to list if he is already in it
  let inArray = employees
    .filter(employee => employee.employeeId === employeeId)
    .length
  if(!inArray) {
    employees.push({employeeId})
  }
  // get index of employee in new array thats filled with employees
  let index = employees.map((el) => el.employeeId).indexOf(employeeId);
  // we need to declare property "devices", but we first have to check if it exists. if it exists, it means it may be filled already, we shouldnt redeclare it because it will overwrite data in it.
  if(!employees[index].devices) {
    employees[index].devices = [];
  }
  // push device in 
  employees[index].devices.push({
    devicetype: initialArray[i].devicetype,
    devicename: initialArray[i].devicename,
    deviceID: initialArray[i].deviceID,
    devicePrimary: initialArray[i].devicePrimary,
  })
}

  console.log(employees);
gogara91
  • 87
  • 5