2016-11-24 61 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:很高兴帮助你:) –