Alejandro Perez Alejandro Perez - 26 days ago 6
Javascript Question

How to create an array of objects from multiple arrays

Given the following arrays:

var ids = [1,2,3]; //Hundreds of elements here
var names = ["john","doe","foo"]; //Hundreds of elements here
var countries = ["AU","USA,"USA"]; //Hundreds of elements here


What's the best way performance-wise to generate an array of objects with a similar structure to this:

var items = [
{id:1,name:"john",country:"AU"},
{id:2,name:"doe",country:"USA"},
...
];

Answer

You should be able to simply map through all ids, keeping a reference to your index, and build your object based on that index.

var items = ids.map((id, index) => {
  return {
    id: id,
    name: names[index],
    country: countries[index]
  }
});