繁体   English   中英

使用包含对象的现有数组的键向对象添加键

[英]Add a key to an object with keys of an existing array with objects

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

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

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

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

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

  $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

您正在尝试访问不存在的阵列成员。

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

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

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

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

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

正确使用这个库,解决了设置和获取变量时可能遇到的许多问题,以及其他超级有用的工具。 在我们的项目中,它对我们来说是一个重要的救生(并节省时间)。

像这样你可以添加

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM