如何在JavaScript中以以下形式转换对象数组? [重复]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在JavaScript中以以下形式转换对象数组? [重复]相关的知识,希望对你有一定的参考价值。

我有以下形式的对象数组,

[
    
        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'
    
]

我正在尝试根据employeeID合并对象属性。因此,如何在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'
  ]
]
答案

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

以上是关于如何在JavaScript中以以下形式转换对象数组? [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何在字符 ASCII 字符串中以数字形式转换 java id? [复制]

对象值的Javascript数组转换为多维数组

如何在 Spring Boot Rest API 中以 XML 形式返回对象列表

如何在Javascript中从数组中提取值

如何在mongodb中以字母数字形式对1000000个元素数组进行排序

javascript多个数组转换成json