【问题标题】:Add a key to an object with keys of an existing array with objects将键添加到具有对象的现有数组的键的对象
【发布时间】:2016-07-18 15:31:23
【问题描述】:

我有一个对象数组array = [object1, object2, ...],每个对象都有一些键object1 = { key1: 'value1', ... }。我想以这种方式添加密钥:

$rootScope.array[i].newKey = 'someValue'

但 Angular 告诉我 $rootScope.array[i]undefined

我从控制台注意到的是对象获得了新的密钥,但控制台仍然显示相同的内容。

【问题讨论】:

  • 您是否将数组添加到您的 $rootScope 中?喜欢$rootScope.array = array;
  • 是的,我确实这样做了$rootScope.meatTypes = [{}];
  • 这意味着肉类类型是一个包含一个空对象的数组。要声明一个空数组,只需使用$rootScope.meatTypes = []

标签: javascript arrays angularjs object


【解决方案1】:

你没有提到lodash,但是当我看到有人遇到这样的问题时,我想提供使用lodash(或underscore.js)的建议。

使用 lodash,您可以使用 _.set 执行类似的操作,它通过自动在路径中添加必要的元素来防御您描述的问题:

_.set($rootScope, ['array', i, 'newKey'], 'someValue');

这个库,如果使用得当,解决了许多你在设置和获取变量时可能遇到的问题,以及其他超级有用的工具。在我们的项目中,它为我们节省了大量生命(和节省时间)。

【讨论】:

    【解决方案2】:

    您应该使用小于而不是小于或等于比较器。

      $scope.init = function () {
            for (i = 0; i < /* not <= */ $rootScope.meatTypes.length; i++) {
                console.log("I am showing the meatypes:");
                console.log($rootScope.meatTypes);
                $rootScope.meatTypes[i].counter = '0';
                counterOperations.setCounters(i, 0);
            }
            $rootScope.total = 0;
            counterOperations.setTopCounter(0);
        };
    

    因为当i 等于$rootScope.meatTypes.length 那么$rootScope.meatTypes[i] 就是undefined

    【讨论】:

      【解决方案3】:

      这样就可以加了

      $rootScope.array[i] = {}; // first we should create an object on that array location
      $rootScope.array[i]['newKey'] = 'someValue'; // then only we can add values
      

      编辑:

      $scope.init = function () {
          for (i = 0; i <= $rootScope.meatTypes.length; i++) {
              console.log("I am showing the meatypes:");
              console.log($rootScope.meatTypes);
              **// This is needed**
              $rootScope.meatTypes[i]={};// here we should tell that metaType[newItem] is an object other wise it treat it as undefined
              $rootScope.meatTypes[i].counter = '0';
              counterOperations.setCounters(i, 0);
          }
          $rootScope.total = 0;
          counterOperations.setTopCounter(0);
      };
      

      【讨论】:

        【解决方案4】:

        您正在尝试访问不存在的数组成员。

        您需要创建一个新对象并将其推送到数组中:

        $rootScope.array.push({'key1': 'someValue'});
        

        【讨论】:

        • 我需要在我的数组的现有对象中创建一个新键,而不是创建一个新对象。
        • 当我实际执行此操作时,我的浏览器崩溃:` $scope.init = function () { for (i = 0; i
        猜你喜欢
        • 1970-01-01
        • 2022-06-10
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-06
        • 2022-06-29
        • 1970-01-01
        相关资源
        最近更新 更多