I would like to take two arrays with an equal number of elements in each, for instance:
colorArr = ['red', 'blue', 'green']
numArr = [1, 2, 3]
... and combine them into one array with object properties that are matched by index:
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]};
});
edited: changed colorArr[index]
to color
as suggested in comment
Use map
method. ( 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.