Nikolay
Nikolay

Reputation: 225

Mysterious "remove" key inserted in my object when populating it

I am iterating over an array(results) and populating an object(testArray). Here's my code for this:

$.each(results, function(key, value)
{
        console.log('value is');
        console.log(value.Id);
        testArray[value.Id] = value;
});
for(var key in testArray) {
            console.log(key);
            console.log(testArray[key].Name);
        }

The problem: When iterating over testArray the last key printed is "remove" and the name associated with it is "undefined". Such a value.Id as "remove" does not exist is never printed from the $.each.

Upvotes: 0

Views: 28

Answers (1)

jfriend00
jfriend00

Reputation: 707776

OK, if it's an object, not an array (your code names it testArray which is really confusing), then you can do this to eliminate enumerable properties that have been added to the prototype:

for (var key in testArray) {
    if (testArray.hasOwnProperty(key)) {
        console.log(testArray[key]);
    }
}

Previous answer when we all though testArray was an array.

This is exactly why you should never be iterating an array with:

for (var key in testArray)

because that iterates all enumerable properties of the array object, not only array elements. You are probably running some code that adds a new method do the array object that is being picked up by your for/in iteration.

Instead use a traditional for loop or use .forEach().

for (var i = 0; i < testArray.length; i++) {
    console.log(testArray[i]);
}

or

testArray.forEach(function(item) {
    console.log(item);
});

These methods will enumerate only actual array elements, not other properties that may have been added to the Array object.

P.S. It's possible to add methods to an Array that will not suffer this problem if they are made non-enumerable, but you should still not ever be iterating an array with for/in. Also, ES6 has a new for/of syntax that can be used safely to iterate arrays, but it requires an ES6 environment.

Upvotes: 2

Related Questions