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

时间:2016-11-11 00:54:28

标签: javascript arrays ecmascript-6

给出以下数组:

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"},
    ...
];

2 个答案:

答案 0 :(得分:3)

您应该能够简单地映射所有ID,保持对索引的引用,并基于该索引构建对象。

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

答案 1 :(得分:-1)

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

[
    { 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)
}

问题是,此结果未按照发问者的要求进行排序。我的意思是不一致的-id是第一项,第二是名称,国家/地区是第三;这样更像样。