javascript tutorial - [Solved-5 Solutions] Enumerate the properties of a javascript object - javascript - java script - javascript array



Problem:

How do We enumerate the properties of a JavaScript object?

Solution 1:

Simple enough:

for(var propertyName in myObject) {
   // propertyName is what we want
   // we can get the value like this: myObject[propertyName]
}
click below button to copy the code. By JavaScript tutorial team

Now, we will not get private variables this way because they are not available.

Solution 2:

Use a for..in loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.

var myObject = {foo: 'bar'};

for (var name in myObject) {
  alert(name);
}

// results in a single alert of 'foo'

Object.prototype.baz = 'quux';

for (var name in myObject) {
  alert(name);
}

// results in two alerts, one for 'foo' and one for 'baz'
click below button to copy the code. By JavaScript tutorial team

To avoid including inherited properties in our enumeration, check hasOwnProperty():

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}
click below button to copy the code. By JavaScript tutorial team

Edit: WE disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that we aren't expecting, because it can change the behavior of our code. It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.

This is why JavaScript provides hasOwnProperty(), and this is why we should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty().

Solution 3:

The standard way, which has already been proposed several times is:

for (var name in myObject) {
  alert(name);
}
click below button to copy the code. By JavaScript tutorial team

However Internet Explorer 6, 7 and 8 have a bug in the JavaScript interpreter, which has the effect that some keys are not enumerated. If we run this code:

var obj = { toString: 12};
for (var name in obj) {
  alert(name);
}
click below button to copy the code. By JavaScript tutorial team

If will alert "12" in all browsers except IE. IE will simply ignore this key. The affected key values are:

  • isPrototypeOf
  • hasOwnProperty
  • toLocaleString
  • toString
  • valueOf

To be really safe in IE we have to use something like:

for (var key in myObject) {
  alert(key);
}

var shadowedKeys = [
  "isPrototypeOf",
  "hasOwnProperty",
  "toLocaleString",
  "toString",
  "valueOf"
];
for (var i=0, a=shadowedKeys, l=a.length; i<l; i++) {
  if map.hasOwnProperty(a[i])) {
    alert(a[i]);
  }
}
click below button to copy the code. By JavaScript tutorial team

The good news is that EcmaScript 5 defines the Object.keys(myObject) function, which returns the keys of an object as array and some browsers (e.g. Safarwe 4) already implement it.

Solution 4:

In modern browsers (ECMAScript 5) to get all enumerable properties we can do: Object.keys(obj) (Check the link to get a snippet for backward compatibility on older browsers) Or to get also non-enumerable properties: Object.getOwnPropertyNames(obj) Check ECMAScript 5 compatibility table

Solution 5:

WE think an example of the case that has caught me by surprise is relevant:

var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
  document.writeln( propertyName + " : " + myObject[propertyName] );
}
click below button to copy the code. By JavaScript tutorial team

But to my surprise, the output is

name : Cody
status : Surprised
forEach : function (obj, callback) {
    for (prop in obj) {
        if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "function") {
            callback(prop);
        }
    }
}
click below button to copy the code. By JavaScript tutorial team

Why? Another script on the page has extended the Object prototype:

Object.prototype.forEach = function (obj, callback) {
  for ( prop in obj ) {
    if ( obj.hasOwnProperty( prop ) && typeof obj[prop] !== "function" ) {
      callback( prop );
    }
  }
};

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Enumerate the properties of a javascript object