2016-11-24 62 views
1

我想推入多維數組中的屬性。 在這段代碼中,我得到類型錯誤:myArr.second [I] .push是不是一個函數...在多維數組中推送屬性

var myArr = { 
"main": 2000, 
"second": [ 
{ 
    "step1": 10, 
    "step2": "lorem ipsum", 
    "step3": "bla, bla", 
    }, 
    { 
    "step1": 20, 
    "step2": "TEXT, TEXT", 
    "step3": "bla, bla, bla", 
}] 
}; 


for(i=0; i < myArr.second.length; i++){ 
    var toPush = {}; 
    toPush["step4"] = "text"; 
    myArr["second"][i].push(toPush); 
} 

任何人可以幫助我嗎?

+0

它的對象,所以你不能在這裏使用推送方法 – Mahi

+0

可能的複製[JavaScript的創建在目標陣列和數據推送到陣列(http://stackoverflow.com/questions/38306219/javascript-creating -array-in-object-and-push-data-to-the-array) – Marcs

+0

「second」是一個數組,你可以在這裏使用push。但myArr是一個對象,而不是一個數組。 'myArr.second [0] .step4 =「text」'應該有效。 – michelgotta

回答

1

使用dot notationbracket notation定義屬性。

for(i=0; i < myArr.second.length; i++){ 
    myArr["second"][i].step4 = "text"; 
} 


或者您可以使用 Object.assign方法從另一個對象複製屬性。

for(i=0; i < myArr.second.length; i++){ 
    var toPush = {}; 
    toPush["step4"] = "text"; 
    Object.assign(myArr["second"][i], toPush); 
} 
+1

謝謝,它工作正常。 – user7206180

+0

@ user7206180:很高興幫助你:) –