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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
You can check it here. This works

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.