0

I am working on an angular app. I am receiving an index from html. Code is as follows:

save(index){
//this method will be called on click of save button
}

In my component I have a array as follow

data = [{
 "name":"Rosy"
},
{
 "name":"julia"
}]

In this save method I want to a add sub array for the index which I receive in save method. Suppose if I get index as 0, then I want to add subarray for 0th index in data array and my resultArray will be as follows:

data = [{
 "name":"Rosy",
  "Address":[{
    "city":"London" // this value I have in a variable in component
  }]
},
{
 "name":"julia"
}]

Suppose, again I receive 0th index, and now city is "mumbai", then data will be added at

data = [{
     "name":"Rosy",
      "Address":[{
        "city":"London" // this value I have in a variable in component
      },
      {
        "city": "mumbai"
      }
]
    },
    {
     "name":"julia"
    }]

Same follows for other indexs and elements. How can I do that?

qqtf
  • 632
  • 6
  • 17
Rosy
  • 17
  • 1
  • 2

1 Answers1

1

Here is a concise function to achieve this.


let componenVar = {"city" : "Mumbai"};

//data is your array

let save = (index) => {
  let part = data[index];
  if(part["Address"]!=undefined){
    part["Address"].push(componenVar);
  }
  else{
    part["Address"] = [componenVar];
    
  }  

}


Since, yours is an array of objects then I can simply take one array element and modify it. It will reflect in the original array. I have assumed index is in bounds. You can modify it further according to your problem statement.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • I think this won't work as I won't get {{"city" : "Mumbai"}; I will just get city name "Mumbai" and in array I need to add it as I shown in example – Rosy Jun 01 '21 at 19:24
  • You can check it [here](https://codepen.io/tusharshahi/pen/ExWozrO). This works – Tushar Shahi Jun 01 '21 at 19:54