将相同长度的数组合并为对象数组 [英] Combine arrays of identical length into array of objects

查看:200
本文介绍了将相同长度的数组合并为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 10 arrays of data that look like this:

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

每个数组每次都具有完全相同数量的元素。我想知道生成组合了不同数组的对象数组的最佳方法:

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]

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

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

推荐答案

这是 Array.map()将是您的朋友。您可以遍历任何数组(因为它们具有相同数量的元素),然后按索引访问每个元素以获取数据集中每个数组的对应值,例如:

This is where Array.map() will be your friend. You can iterate through any of the arrays (since they have the same number of elements) and then access each element by index to get the corresponding value for each array in your dataset, like so:

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);

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

If you wanted to access them generically, you can add all of your arrays to one dictionary and iterate over the key/value pairs, like so:

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);

这篇关于将相同长度的数组合并为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆