Home > Net >  Angular change a value from a js object
Angular change a value from a js object

Time:01-06

I am using angular and I have some data:

export class AppComponent {

data = [ 
    {
      "area1": {
        "format": "changethis"
    }
]

I want to create a method that will change the value of a key. For example:

  changeKeyValue() {
    const key = data[0].area1.format;
    const value = 'someOtherValue';
    // Code to do the change here
  }

}

How can I do this?

CodePudding user response:

If you want to update a specific item in the array, you can specify the index data[0] or data[index] and update it

data = [ 
    {
      "area1": {
        "format": "changethis"
      }
    }
]

let value = "New value"  
data[0].area1.format = value;

or

data[0].area1["format"] = value;

If you want to update all "format" attribute in your array, you can use any of the array method and iterate through it to update all values

eg

data.forEach(item=>item.area1.format = 'new text')
  •  Tags:  
  • Related