Updating array object values

I want to update some values ​​in a global array that are stored in a factory. I use the get method to get the data, but the set function somehow does not do its job, and the value in the array is not updated. What am I missing?

.factory('messageList', function () {
   var Messages = 
    [
        {   "title":"Cash in", "icon":"ion-social-euro", 
            "dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0", 
            "category": "financial", "active": "true"
        },
        {   "title":"Sales orders", "icon":"ion-social-euro", 
            "dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0", 
            "category": "sales", "active": "true"
        }
    ]

return {
   get: function() {
      return Messages;
   },
   set: function(title, key, newValue) {
       for (var i = 0; i < Messages.length; i++) {
          if(Messages[i].title == title){
            Messages[i].key = newValue;
          }
       }
   }
 }
})

This is how I try to update the values ​​in the controller:

messageList.set("Sales orders","dailyValue", $Scope.sum);
+4
source share
1 answer

Since keyis a variable, use this

Messages[i][key] = newValue;

Messages[i].key will look for an element in your object with a key of a key, not a key with a variable value

+5
source

Source: https://habr.com/ru/post/1615866/


All Articles