簡體   English   中英

將兩個 arrays 合並為一個具有 object 結構的數組

[英]Combine two arrays into one array with object structure

我想取兩個 arrays ,每個元素的數量相等,例如:

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

...並將它們與索引匹配的 object 屬性組合成一個數組:

newArr = [
  {'Color' : 'red', 'Number' : 1}, 
  {'Color' : 'blue', 'Number' : 2}, 
  {'Color' : 'green', 'Number' : 3}
]
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

使用map方法。 陣列.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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM