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