2016-11-11 84 views
0

考虑下面的数组的数组:如何创建对象,从多个阵列

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

如果有一件事我不能说足够的话,就是这样:先让它工作,然后担心**和**只有当**性能成为问题。如果你不关心表现,你会如何解决这个问题? – kevin628

+0

什么样的表现?运行?记忆?代码行?可写/可维护性? – 2016-11-11 03:53:58

+0

我想知道你在哪里陷入困境,因为一个简单的解决方案是从0循环到2,然后每次通过循环将包含相关值的对象推送到结果数组上。一旦你知道了,你可以继续使用'map'等。 – 2016-11-11 03:56:36

回答

3

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

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