繁体   English   中英

如何从多个 arrays 创建对象数组

[英]How to create an array of objects from multiple 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

生成具有类似结构的对象数组的最佳性能方式是什么:

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

您应该能够简单地映射所有 id,保留对索引的引用,并根据该索引构建对象。

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

这是我运行代码时得到的:

[
    { country=AU, name=john, id=1.0 }, 
    { name=doe, country=USA, id=2.0 }, 
    { id=3.0, country=USA, name=foo }
]

以下是代码,与@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)
}

问题是,这个结果没有按照提问者的要求排序。 我的意思是它不一致 - ids 是第一项,名称第二,国家第三; 这样它更像样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM