0

I have a simple for loop like so :

for(var foo in bar) {
    var x = bar[foo];
    console.log(x);
}

However, I get this as my response:

{...} // An object as expected
{...} // An object as expected
{...} // An object as expected
[Function]

What is this extra function and how can we remove it?

davewoodhall
  • 998
  • 3
  • 18
  • 43
  • Probably some other property of `bar` that you don't want, [as described here](http://stackoverflow.com/questions/684672/loop-through-javascript-object) – ssube May 20 '15 at 17:21
  • Could you post sample bar? – vjdhama May 20 '15 at 17:21
  • `hasOwnProperty` is your friend – mkoryak May 20 '15 at 17:21
  • What’s the name of the key (`console.log(foo, x)`)? If it’s on `Object.prototype`, 1) use a filtered loop with `hasOwnProperty` 2) don’t extend `Object.prototype` with enumerable properties 3) don’t extend `Object.prototype` 4) use `Object.keys(bar).forEach` instead – Ry- May 20 '15 at 17:21
  • @ssube how is hasOwnProperty different from `typeof `? I've added `if (typeof x == 'undefinded') continue;` but that doesn't do it; I had to do `if (typeof x == 'undefinded' || typeof x == 'function') continue;` to get it to work. Somehow, I don't think that both typeofs are necessary – davewoodhall May 20 '15 at 17:50
  • @DaveWoodhall `hasOwnProperty` ensures that the property is defined on the instance, not provided by inheritance. It skips prototype methods and the like. – ssube May 20 '15 at 17:51

1 Answers1

0

The extra function is likely the object prototypes constructor, use hasOwnProperty to check for the property in your loop.

Stradosphere
  • 1,285
  • 3
  • 14
  • 40