javascript - 将相同长度的数组组合成对象数组

标签 javascript arrays

我有 10 个如下所示的数据数组:

var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays

每个数组每次都将具有完全相同数量的元素。我想知道生成一个看起来像这样的对象数组的最佳方法,它结合了各种数组:
overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]

我认识到我可以使用大量 for 循环,但我正在寻找有人可能拥有的更优化的解决方案。

最佳答案

这是Array.map()会是你的 friend 。您可以遍历任何数组(因为它们具有相同数量的元素),然后通过索引访问每个元素以获取数据集中每个数组的相应值,如下所示:

var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];

let mapped = arr.map((elem, index) => {
  return {
    arr1: arr[index],
    arr2: arr2[index],
    arr3: arr3[index]
  }
});

console.log(mapped);


编辑:如果您想一般地访问它们,您可以将所有数组添加到一个字典并遍历键/值对,如下所示:

var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
// combine all arrays into single dataset
let data = {arr, arr2, arr3};

let mapped = arr.map((elem, index) => {
  // iterate over the key/value pairs of the dataset, use the key to generate the 
  // result object key, use the value to grab the item at the current index of the 
  // corresponding array
  return Object.entries(data).reduce((res, [key, value]) => {
    res[key] = value[index];
    return res;
  }, {});
});

console.log(mapped);

关于javascript - 将相同长度的数组组合成对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233001/

相关文章:

javascript - 如何延迟加载 Canvas 元素

javascript - 如何从函数node.js内部使变量成为全局变量?

javascript - 单击表单中的提交按钮时,将焦点放在空白字段上

javascript - D3v4力向图-localStorage断开链接和节点

python - 调用数组时仅使用第一个元素?

javascript - 在 javascript 中使用二维数组并尝试从中读取值给出 "Uncaught TypeError: Cannot read property ' 0' of undefined"

python - numpy loadtxt 增量加载以保留内存?

javascript - Socket.io 消息事件多次触发

c - 打印 C 中函数返回的字符数组

php - 将具有单个键和字符串值的数组拆分为具有多个键和值的数组