1

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.

2 Answers 2

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

Hope I helped ;)

For future reference: MDN

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Great answer, but @komnions answer was more along the lines of what I was looking for. But I still gave you an "up".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.