将一个已有对象数组中的键添加到一个对象中。

3

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

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

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

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


你是否将数组添加到了 $rootScope 中?例如 $rootScope.array = array; - Lulylulu
是的,实际上我执行了 $rootScope.meatTypes = [{}]; - korteee
这意味着meat types是一个包含一个空对象的数组。要声明一个空数组,只需使用$rootScope.meatTypes = [] - Lulylulu
4个回答

3

您应该使用比较运算符小于而不是小于等于

  $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

2

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

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

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

我需要在现有数组对象中创建一个新的键,而不是创建一个新的对象。 - korteee
当我实际执行此操作时,我的浏览器崩溃: $scope.init = function () { for (i = 0; i <= $rootScope.meatTypes.length; i++) { console.log("I am showing the meatypes:"); console.log($rootScope.meatTypes); $rootScope.meatTypes.push({'counter':0}); counterOperations.setCounters(i, 0); } $rootScope.total = 0; counterOperations.setTopCounter(0); }; - korteee

1

您没有提及 lodash,但是当我看到有人遇到这样的问题时,我想推荐使用 lodash(或 underscore.js)。

使用 lodash,您可以像这样使用 _.set,它通过自动添加路径中必要的元素来防御性地保护您所描述的问题:

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

这个库,如果正确使用,可以解决许多设置和获取变量的问题,以及其他超级有用的工具。它在我们的项目中是一个重要的救命稻草(也是时间节省者)。


0

像这样,您可以添加

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接