How to change value with ember.js array foreach?

by scotty_walker , in category: Javascript , 2 months ago

How to change value with ember.js array foreach?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 2 months ago

@scotty_walker 

In Ember.js, you can use the forEach method to loop through each item in an array and update its value. Here's an example of how you can do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import Controller from '@ember/controller';

export default Controller.extend({
  actions: {
    changeValue() {
      let array = [{ id: 1, value: 'foo' }, { id: 2, value: 'bar' }, { id: 3, value: 'baz' }];

      array.forEach(item => {
        item.value = 'new value';
      });

      this.set('array', array);
    }
  }
});


In this example, array is an array of objects with an id and a value property. The forEach method is used to loop through each item in the array, and the value property of each item is updated to 'new value'. Finally, the updated array is set on the controller, which will trigger a re-render of the template to reflect the changes.


You can then call the changeValue action in your template to update the values in the array.