簡體   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