JavaScript - 从多个数组创建对象

标签 javascript arrays

我有 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/

相关文章:

javascript - DKfindout.com(网站)如何对图像进行注释?

arrays - Golang问题数组数独-网格[i] [j] [0]

java - 对象数组,Java和C++的区别

javascript - 使用 Node 和 TypeScript 开 Jest - 检查 Singleton 中静态方法的抛出错误

javascript - Angular2 + 引导网格

javascript - 谷歌地图 Geojson 信息窗口

javascript - 为什么 Javascript 不能在附加模式下工作?

php - 如何在 PHP 中更改数组结构

arrays - 选择最接近零的元素

ios - 数组已填充,但括号外为空?