将两个数组合并为具有对象结构的一个数组

时间:2020-07-22 03:54:27

标签: javascript arrays methods

我想采用两个数组,每个数组中元素的数量相等,例如:

colorArr = ['red', 'blue', 'green']
numArr = [1, 2, 3]

...并将它们组合成一个具有与索引匹配的对象属性的数组:

newArr = [
  {'Color' : 'red', 'Number' : 1}, 
  {'Color' : 'blue', 'Number' : 2}, 
  {'Color' : 'green', 'Number' : 3}
]

2 个答案:

答案 0 :(得分:1)

const colorArr = ['red', 'blue', 'green'];
const numArr = [1, 2, 3];

let newArr = colorArr.map((color, index) => {
    return {"Color": color, "Number": numArr[index]};
});

已编辑:已按照评论中的建议将colorArr[index]更改为color

答案 1 :(得分:0)

使用map方法。 (Array.map

colorArr = ["red", "blue", "green"];
numArr = [1, 2, 3];

// map over colorArr and get values from numArr
const output = colorArr.map((Color, i) => ({ Color, Number: numArr[i] }));
console.log(output);


// Alternatively, map over numArr and get values from colorArr
const output2 = numArr.map((Number, i) => ({ Color: colorArr[i], Number }));
console.log(output2)