2017-07-18 76 views
1

我無法從單獨的數組更新對象值。使用JavaScript中的單個數組更新數組對象

例子:

mainArray = [ 
    { "name": "bob", "complete": "25" }, 
    { "name": "john", "complete": "50" }, 
    { "name": "mike", "complete": "75" },   
]; 

colorArray = ["#ff0000", "#00ff00", "#0000ff"]; 

我需要創建一個新的磁盤陣列,結合這些值。

for (i = 0, ilen = mainArray.length; ilen > i; i++) { 
    newArray.push({ 
     name: mainArray[i].name, 
     complete: mainArray[i].complete, 
     color: '', 
    }); 
} 

無論我做什麼,我要麼只得到#0000ff,要麼根本得不到任何工作。失敗的嘗試:

for (j = 0, jlen = newArray.length; jlen > j; j++) { 
    for (k = 0, km = colorArray.length; km > k; k++) { 
     newArray[j].color = colorArray[k]; 
    } 
} 

目標是要取回:

newArray = [ 
    { "name": "bob", "complete": "25", "color": "#ff0000" }, 
    { "name": "john", "complete": "50", "color": "#00ff00" }, 
    { "name": "mike", "complete": "75", "color": "#0000ff" }   
]; 

什麼是做這種正確的方法是什麼?

回答

4

只需根據colorArray的索引設置每個人的color密鑰。

var mainArray = [ 
    { "name": "bob", "complete": "25" }, 
    { "name": "john", "complete": "50" }, 
    { "name": "mike", "complete": "75" },   
]; 
var colorArray = ["#ff0000", "#00ff00", "#0000ff"]; 
var newArray = []; 

for (var i = 0; i < mainArray.length; i++) { 
    newArray.push({ 
    name: mainArray[i].name, 
    complete: mainArray[i].complete, 
    color: colorArray[i] 
    }); 
} 
+0

這很有效,謝謝。我仍然不明白在這種情況下JavaScript如何通過索引來「循環」我的顏色數組。我應該在文檔/參考文獻中看到什麼? – DusmaN

+1

當你使用像'i'這樣的索引的循環時,不要認爲它是循環遍歷數組,而是將它想象成循環遍歷一系列值。在這種情況下,通過循環第一次,'i'爲0,然後1,然後2,然後停止,因爲比較'3

+0

@FelixGuo很好的解釋 – m0meni

0

使用Array.mapObject.assign功能更強大的方法看起來像

var mainArray = [ 
 
    { "name": "bob", "complete": "25" }, 
 
    { "name": "john", "complete": "50" }, 
 
    { "name": "mike", "complete": "75" },   
 
]; 
 
var colorArray = ["#ff0000", "#00ff00", "#0000ff"]; 
 

 
var newArray = mainArray.map((x, i) => 
 
    Object.assign({}, x, {color: colorArray[i]}) 
 
) 
 
    
 
console.log(newArray);

0

您有以下不必要的嵌套循環:

for (j = 0, jlen = newArray.length; jlen > j; j++) { 
    for (k = 0, km = colorArray.length; km > k; k++) { 
     newArray[j].color = colorArray[k]; 
    } 
} 

您可以將其更改爲:

for (j = 0, jlen = newArray.length; jlen > j; j++) { 
    newArray[j].color = colorArray[j]; 
}