如何在javascript中将两个相同长度的数组转换为一个对象数组?

时间:2020-12-31 12:18:44

I have two arrays that look like this:

我有两个像这样的数组:

array1 = [1, 2, 3, 4, 5];
array2 = [a, b, c, d, e];

Using JavaScript, I want to convert two arrays of same length into array of objects that would look like this:

使用JavaScript,我想将两个相同长度的数组转换成如下所示的对象数组:

newArrayofObjects = [ {key1: 1, key2: a}, {key1: 2, key2: b}, {key1: 3, key2: c},  {key1: 4, key2: d}, {key1: 5, key2: e}] 

2 个解决方案

#1


4  

Array.map comes in handy a lot.

数组中。地图经常派上用场。

var newArray = array1.map(function(e,i){return{key1:e,key2:array2[i]}});

#2


2  

var array1 = [1, 2, 3, 4, 5], array2 = ['a', 'b', 'c', 'd', 'e'], newArrayofObjects = [];
for(var key = 0; key < array1.length; key++) {
    newArrayofObjects.push({key1 : array1[key], key2 : array2[key]});
}

#1


4  

Array.map comes in handy a lot.

数组中。地图经常派上用场。

var newArray = array1.map(function(e,i){return{key1:e,key2:array2[i]}});

#2


2  

var array1 = [1, 2, 3, 4, 5], array2 = ['a', 'b', 'c', 'd', 'e'], newArrayofObjects = [];
for(var key = 0; key < array1.length; key++) {
    newArrayofObjects.push({key1 : array1[key], key2 : array2[key]});
}