2016-11-11 83 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] 
    } 
});