user7206180 user7206180 - 16 days ago 7
Javascript Question

push property in multidimensional array

i want to push property in multidimensional array.
In this code i get TypeError: myArr.second[i].push is not a function...

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);
}


Can anybody help me?

Answer

Use dot notation or bracket notation to define property.

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


Or you can use Object.assign method to copy properties from another object.

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