Dustin Poissant
Dustin Poissant

Reputation: 3418

How to access the properties of a JavaScript object using a "for in" loop when they are defined with `Object.defineProperty`

I have a JavaScript object that has some properties that were created using the Object.defineProperty function. I would like to iterate through all of it's properties using the "for in" method, but these properties are ignored. Is there another way I can do this?

var myObject = {
  prop1: "This is property 1",
  prop2: "This is property 2"
};
(function(){
  var prop3 = "This is a read only property";
  Object.defineProperty(myObject, "prop3", {
    get: function(){
      return prop3;
    },
    set: function(){
      console.warn('"myObject.prop3" is read only.');
    }
  });
})();

alert("Property 3 = " + myObject.prop3);

for(var k in myObject){
  alert(myObject[k]);
}

The first alert shows us that "prop3" is a real property that was defined with Object.defineProperty, but then when we iterate through the properties using a "for in" loop "prop3" is ignored.

Upvotes: 1

Views: 33

Answers (2)

Luka
Luka

Reputation: 3089

This is not with for in loop, but maybe is still good enough for you. You can get those property names with Object.getOwnPropertyNames, and then loop through them:

var propNames = Object.getOwnPropertyNames(myObject);
for(var i=0; i<propNames.length; i++) {
    alert(myObject[propNames[i]]);
}

Upvotes: 1

Komninos
Komninos

Reputation: 424

Object.defineProperty(myObject, 'prop3', {
  enumerable: true
});

Hope I helped ;)

For future reference: MDN

Upvotes: 3

Related Questions