我有两个数组:

arr1 = [name, speed, power, energy];
arr2 = [
  [Ed, 10, 20, 30],
  [Robert, 15, 25, 35],
  [Paul, 8, 18, 28]
];


如何使用第一个数组作为键,第二个数组用于值,将两个数组组合为一个对象数组?

arr3 = [
  {
    name: "Ed",
    speed:"10",
    power:"20",
    energy:"30"
  },
  {
    name: "Robert",
    speed:"15",
    power:"25",
    energy:"35"
  },
  {
    name: "Paul,
    speed:"8",
    power:"18",
    energy:"28"
  }
];

最佳答案

您可以使用map轻松创建对象数组

arr2.map(row => {
 const name = item[0];
 const speed = item[1];
 const power = item[2];
 const energy = item[3];
 return { name, speed, power, energy }
})


在给定的arr2上运行此命令可获得以下结果

var arr2 = [['Ed', 10, 20, 30],['Robert', 15, 25, 35],['Paul', 8, 18, 28]];

var arr3 = arr2.map(row => {
 const name = item[0];
 const speed = item[1];
 const power = item[2];
 const energy = item[3];
 return { name, speed, power, energy }
});

console.log(arr3)
// arr3 = [
//  {name: "Ed", speed:10, power:20, energy:30},
//  {name: "Robert", speed:15, power:25, energy:35},
//  {name: "Paul", speed:8, power:18, energy:28}
// ]

08-15 18:09