korteee
korteee

Reputation: 2682

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

I've got an array of objects array = [object1, object2, ...], each of them has some keys object1 = { key1: 'value1', ... }. I want to add a key this way:

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

But angular tells me that $rootScope.array[i] is undefined.

What I've noticed from console is that the objects get the new key but the console still says the same.

Upvotes: 3

Views: 123

Answers (4)

random_user_name
random_user_name

Reputation: 26160

You did not mention lodash, but when I see someone encounter an issue like this, I want to offer the recommendation of using lodash (or underscore.js).

With lodash, you would do something like so, using _.set, which defensively protects against your described issue by automatically adding the necessary elements in the path:

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

This library, properly utilized, solves many issues that you can have with setting and getting variables, ase well as other super useful tools. It has been a major life-saver (and time-saver) for us on our projects.

Upvotes: 1

Lulylulu
Lulylulu

Reputation: 1264

You should use less than and not less or equal than comparator.

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

because when i equals $rootScope.meatTypes.length then $rootScope.meatTypes[i] is undefined.

Upvotes: 3

saravanakumar
saravanakumar

Reputation: 1777

Like this you can add

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

EDIT:

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

Upvotes: 0

David L
David L

Reputation: 33833

You are trying to access a member of the array that does not exist.

You need to create a new object and push it onto the array:

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

Upvotes: 2

Related Questions