2017-06-12 109 views
0

創建單個對象我有兩個相同長度的陣列使用兩個陣列

ids = [123, 456, 789, ...., 999]; 
names = ['foo', 'bar', ... , 'zzz']; 

我想創建像

[ {id: 123, name: 'foo'}, {id: 123, name: 'bar'}, ..., {id: 999, name: 'zzz'} ] 

我試圖避免forEach如果可能的數組。

有什麼建議嗎?

回答

2

map好嗎?

ids = [123, 456, 789, 999]; 
 
names = ['foo', 'bar', 'baz', 'zzz']; 
 

 
result = ids.map(function(_, i) { 
 
    return {id: ids[i], name: names[i]} 
 
}); 
 

 
console.log(result)

+0

這次是或多或少我的回答也是如此。只是想爲OP添加一個免責聲明,即使用兩個獨立數組,可能會出現一個數組與另一個數組的長度不相等的情況,在這種情況下,您最終可能不會將每個數組創建爲文字,或者更糟糕,'ids'數組比'names'有更多的元素,這會導致索引超出範圍的錯誤。 –

0

如果你不希望使用任何高階函數,那麼就這樣做:

var objects = []; 
for (var i = 0; i < ids.length; i++) { 
    objects.push({id: ids[i], name: names[i]}); 
} 
0

無需forEach這裏。使用map,與forEach類似。

var ids = [123, 456, 999]; 
 
var names = ['foo', 'bar', 'zzz']; 
 

 
var result = ids.map(function (currentId, index) { 
 
    return { 
 
    id: currentId, 
 
    name: names[index] 
 
    }; 
 
}); 
 

 
console.log(result);

forEach版本是這樣的(注意,他們是多麼相似):

var ids = [123, 456, 999]; 
 
var names = ['foo', 'bar', 'zzz']; 
 

 
var result = []; 
 
ids.forEach(function(currentId, index) { 
 
    result.push({ 
 
    id: currentId, 
 
    name: names[index] 
 
    }); 
 
}); 
 

 
console.log(result);

0

下面的代碼使用foreach但你不需要來處理它。我希望這會對你有用。

ids = [123, 456, 789, 999]; 
 
    names = ['foo', 'bar', 'zab', 'zzz']; 
 
    
 
    result = ids.map(function(_, i) { 
 
     return {id: ids[i], name: names[i]} 
 
    }); 
 
    
 
    console.log(result)