オブジェクトの配列に同一の長さの配列を組み合わせます

ダコタブラウン:

私はこのようになり、データの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'
...
}]

私は、ループのための大規模な番号を使用できることを認識誰かが持っている可能性があることをより最適化されたソリューションを探しています。

mhodges:

これはどこでArray.map()あなたの友人になります。あなたは(彼らは同じ数の要素を持っているので)の配列のいずれかを反復して、そのように、あなたのデータセット内の各列に対応する値を取得するには、インデックスによって各要素にアクセスすることができます。

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

編集:あなたは一般的にそれらにアクセスしたい場合は、次のようなので、キー/値のペアの上に1つの辞書と反復する、あなたのすべてのアレイを追加することができます。

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=7724&siteId=1