2

I want to create an object to hold a bunch of properties like

var o = {x: 20, y: 40, color: 'red'};

More properties can be added to the object throughout its life, so I would like a generic way to loop over the properties to set them later. I know if the Object.prototype has been messed with, simply

for(var prop in o) { ... }

will cause its properties to also be looped over. What other things can cause this to mess up, and what is the safest way to loop like this?

Jeremy
  • 1
  • 77
  • 324
  • 346
Davis Dimitriov
  • 3,519
  • 3
  • 27
  • 44
  • Take a look at [this post][1], you pretty much said it in your question. [1]: http://stackoverflow.com/questions/242841/javascript-foreach-vs-for – George P Jul 28 '11 at 22:15
  • @Davis if you follow the link from George P pay attention to the answer by Bno because it, and not the accepted answer, mentions the `hasOwnProperty` technique which saves you from the case in which `Object.prototype` has been messed with, and is considered a best practice, at least by *Good Parts* adherents. – Ray Toal Jul 28 '11 at 22:21

3 Answers3

7

If you want to iterate over all of the properties on an object, then inherited properties are the only real problem you have to deal with. The Object.prototype.hasOwnProperty() method can be used to confirm that a property exists directly an object, and isn't just inherited.

Object.prototype.example = 2;
var o = {x: 4, y: 6};

for (var prop in o) {
    if (Object.prototype.hasOwnProperty.call(o, prop)) {
        console.log(o[prop]);
    }
}

This will print all of the properties of the object itself, but it won't print the inherited .example.

Jeremy
  • 1
  • 77
  • 324
  • 346
6

As an alternative to what @Jeremy Banks suggested, Object.keys method does return only "own" property names of an object, too. Hence an ES5 solution:

var o = { x: 20, y: 40, color: 'red' };

Object.keys(o).forEach(function (prop) { /* ... */ });
katspaugh
  • 15,752
  • 9
  • 61
  • 97
1

Use object.hasOwnProperty()

var buz = {
    fog: 'stack'
};

for (var name in buz) {
    if (buz.hasOwnProperty(name)) {
        alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
    }
    else {
        alert(name); // toString or something else
    }
}

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Example.3a_Iterating_over_the_properties_of_an_object

Ryan Doherty
  • 37,071
  • 3
  • 51
  • 62