更新数组对象值 [英] Updating array object values

查看:24
本文介绍了更新数组对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新我保存在工厂中的全局数组中的一些值.我使用 get 方法来获取数据,但 set 函数以某种方式没有完成它的工作,并且数组中的值没有得到更新.我错过了什么?

I want to update some values in global array that I keep in a factory. I use the get method to get the data but set function somehow doesn't do its job and the value in the array doesn't get 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 attempt to update the values in the controller:

messageList.set("Sales orders","dailyValue", $Scope.sum);

推荐答案

由于 key 是一个变量,所以使用这个

As key is a variable, use this

Messages[i][key] = newValue;

Messages[i].key 将在你的对象中寻找一个带有键key"的元素,而不是一个带有变量值的键

Messages[i].key will look for an element in your object with key 'key' rather than a key with the value of your variable

这篇关于更新数组对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆