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"},
...
];
Andrew Li
58.1k14 gold badges136 silver badges150 bronze badges
asked Nov 11, 2016 at 0:54
Alejandro Perez
611 gold badge1 silver badge4 bronze badges
2 Answers 2
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]
}
});
answered Nov 11, 2016 at 0:59
Zack Tanner
2,5801 gold badge29 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
Martin Brisiak
4,11112 gold badges40 silver badges51 bronze badges
1 Comment
Shane
Just want to add that the ordering of fields in an object is not guaranteed. As per the JSON standard, "An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array." - rfc-editor.org/rfc/rfc8259.html#section-1
lang-js
mapetc.