Combine arrays of identical length into array of objects

Dakota Brown :

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'
...
}]

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

mhodges :

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

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7109&siteId=1