我有 3 个数组:
colors = ['green', 'red', 'black'];
positionToId = [0, 32, 15];
results = ["0", "1", "2"];
并且想要实现这样的目标:
{results: '0', 'positionToId: '31', colors: 'black'},
{results: '1', 'positionToId: '2', colors: 'red'},
{results: '2', 'positionToId: '11', colors: 'black'}
我该怎么做? 谢谢。
最佳答案
您想将这些数组合并为一个对象数组,该数组具有key => value
。
最简单的方法是 map
其中之一。
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
例子:
colors = ['green', 'red', 'black'];
positionToId = [0, 32, 15];
results = ["0", "1", "2"];
console.log(results.map((result,i) => {
return {
results: results[i],
positionToId: positionToId[i],
colors: colors[i],
};
}));
关于JavaScript - 从多个数组创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245057/