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"},
...
];
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"},
...
];
Share
Improve this question
edited Nov 11, 2016 at 0:56
Andrew Li
58k14 gold badges134 silver badges148 bronze badges
asked Nov 11, 2016 at 0:54
Alejandro PerezAlejandro Perez
611 gold badge1 silver badge4 bronze badges
3
|
2 Answers
Reset to default 20You 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]
}
});
This is what I get when run the code:
[
{ country=AU, name=john, id=1.0 },
{ name=doe, country=USA, id=2.0 },
{ id=3.0, country=USA, name=foo }
]
Following is the code, same as @Zack Tanner
function arrs2Obj() {
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
var items = ids.map((id, index) => {
return {
id: id,
name: names[index],
country: countries[index]
}
});
Logger.log(items)
}
The problem is, this result is not sorted as the questioner asked. I mean it's not consistent - ids to be the first item, name second, country 3rd; this way it is more presentable.
map
etc. – user663031 Commented Nov 11, 2016 at 3:56