deszok
deszok

Reputation: 175

Angular change a value from a js object

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?

Upvotes: 0

Views: 41

Answers (1)

Syam
Syam

Reputation: 323

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')

Upvotes: 1

Related Questions