[英]How to create an array of objects from multiple arrays
Given the following arrays:给定以下 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"},
...
];
You should be able to simply map through all ids, keeping a reference to your index, and build your object based on that index.您应该能够简单地映射所有 id,保留对索引的引用,并根据该索引构建对象。
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以下是代码,与@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;
我的意思是它不一致 - ids 是第一项,名称第二,国家第三; this way it is more presentable.
这样它更像样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.