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

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

问题描述

我要更新全局数组中的一些价值观,我保持在一个工厂。
我使用get方法来获取数据,但不知何故设置功能没有做其工作,并在数组中的价值没有得到更新。我缺少什么?

  .factory('给messageManager',函数(){
   VAR消息=
    [
        {称号:现金,图标:离子社会欧元,
            dailyValue:0,weeklyValue:0,monthlyValue:0,
            类别:财经,主动:真
        },
        {称号:销售订单,图标:离子社会欧元,
            dailyValue:0,weeklyValue:0,monthlyValue:0,
            类别:销售,主动:真
        }
    ]返回{
   得到:函数(){
      返回消息;
   },
   设置:功能(标题,关键字,为newValue){
       对于(VAR I = 0; I< Messages.length;我++){
          如果(消息[I] .title伪==标题){
            消息[I] .KEY =为newValue;
          }
       }
   }
 }
})

这是我尝试更新控制器的值:

  messageList.set(销售订单,dailyValue,$ Scope.sum);


解决方案

由于是一个变量,使用

 信息[I] [关键] =为newValue;

信息[I] .KEY 将寻找一个元素在你的目标与关键的钥匙,而不是价值的一个关键你的变量

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

解决方案

As key is a variable, use this

Messages[i][key] = newValue;

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天全站免登陆