简体   繁体   English

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

[英]How to convert two arrays of same length into one array of objects in javascript?

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}] 

Array.map非常有用。

var newArray = array1.map(function(e,i){return{key1:e,key2:array2[i]}});
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]});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将两个数组转换为一个对象,Javascript中每个数组的键相同 - Convert two arrays to one object, with same key for each array in Javascript 如何在 javascript 中将对象数组转换为 arrays 数组 - How to convert array of objects to array of arrays in javascript 将两个对象转换为一个数组 (JavaScript) - Convert two objects into one array (JavaScript) 如何在javascript中将两个数组组合成一个对象数组? - How to combine two arrays into an array of objects in javascript? 如何合并来自两个相同长度的不同数组的对象? - How to merge objects from two different arrays of same length? 如何将多个对象转换为单个数组并计算javascript中对象的长度? - How to convert multiple objects to a single array and count the length of the objects in javascript? 合并JavaScript中相同长度的多个对象数组 - Merging multiple arrays of objects of the same length in JavaScript 如何将对象的对象数组转换为一维数组? - How to convert Arrays of objects of objects into one dimensional array? 如何将两个数组合并为一个? 保留数组元素和长度 - How to merge two arrays into one? Retain array elements and length JavaScript 如何通过两个不同的 arrays 对象并有条件地返回一个数组 - JavaScript how to map through two different arrays of objects and return one array conditionally
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM