[javascript] How do I enumerate the properties of a JavaScript object?

How do I enumerate the properties of a JavaScript object?

I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.

This question is related to javascript properties

The answer is


If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually.

Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values.

var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
Object.toJSON(data);
//-> '{"name": "Violet", "occupation": "character", "age": 25, "pets": ["frog","rabbit"]}'

http://www.prototypejs.org/api/object/tojson


I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..


You can use the for of loop.

If you want an array use:

Object.keys(object1)

Ref. Object.keys()


for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}

I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..


Here's how to enumerate an object's properties:

var params = { name: 'myname', age: 'myage' }

for (var key in params) {
  alert(key + "=" + params[key]);
}

I'm still a beginner in JavaScript, but I wrote a small function to recursively print all the properties of an object and its children:

getDescription(object, tabs) {
  var str = "{\n";
  for (var x in object) {
      str += Array(tabs + 2).join("\t") + x + ": ";
      if (typeof object[x] === 'object' && object[x]) {
        str += this.getDescription(object[x], tabs + 1);
      } else {
        str += object[x];
      }
      str += "\n";
  }
  str += Array(tabs + 1).join("\t") + "}";
  return str;
}

for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}

Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:

function keys(){
    var k = [];
    for(var p in this) {
        if(this.hasOwnProperty(p))
            k.push(p);
    }
    return k;
}
Object.defineProperty(Object.prototype, "keys", { value : keys, enumerable:false });

EDIT: But the answer of @carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.

EDIT after 5 years: it is not good idea to extend Object, because it can conflict with other libraries that may want to use keys on their objects and it will lead unpredictable behavior on your project. @carlos-ruana answer is the correct way to get keys of an object.


If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually.

Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values.

var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
Object.toJSON(data);
//-> '{"name": "Violet", "occupation": "character", "age": 25, "pets": ["frog","rabbit"]}'

http://www.prototypejs.org/api/object/tojson


I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..


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

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

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 you run this code:

var obj = { toString: 12};
for (var name in obj) {
  alert(name);
}

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

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. Safari 4) already implement it.


You can use the for of loop.

If you want an array use:

Object.keys(object1)

Ref. Object.keys()


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'

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

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I 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 you aren't expecting, because it can change the behavior of your 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 you 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().


If you are using the Underscore.js library, you can use function keys:

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

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'

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

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I 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 you aren't expecting, because it can change the behavior of your 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 you 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().


Here's how to enumerate an object's properties:

var params = { name: 'myname', age: 'myage' }

for (var key in params) {
  alert(key + "=" + params[key]);
}

If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually.

Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values.

var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
Object.toJSON(data);
//-> '{"name": "Violet", "occupation": "character", "age": 25, "pets": ["frog","rabbit"]}'

http://www.prototypejs.org/api/object/tojson


Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:

function keys(){
    var k = [];
    for(var p in this) {
        if(this.hasOwnProperty(p))
            k.push(p);
    }
    return k;
}
Object.defineProperty(Object.prototype, "keys", { value : keys, enumerable:false });

EDIT: But the answer of @carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.

EDIT after 5 years: it is not good idea to extend Object, because it can conflict with other libraries that may want to use keys on their objects and it will lead unpredictable behavior on your project. @carlos-ruana answer is the correct way to get keys of an object.


In modern browsers (ECMAScript 5) to get all enumerable properties you 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

Additional info: What is a enumerable attribute?


If you are using the Underscore.js library, you can use function keys:

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

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'

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

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I 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 you aren't expecting, because it can change the behavior of your 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 you 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().


for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}

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'

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

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I 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 you aren't expecting, because it can change the behavior of your 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 you 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().


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

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

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 you run this code:

var obj = { toString: 12};
for (var name in obj) {
  alert(name);
}

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

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. Safari 4) already implement it.


Simple JavaScript code:

for(var propertyName in myObject) {
   // propertyName is what you want.
   // You can get the value like this: myObject[propertyName]
}

jQuery:

jQuery.each(obj, function(key, value) {
   // key is what you want.
   // The value is in: value
});

I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..


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

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

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

In modern browsers (ECMAScript 5) to get all enumerable properties you 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

Additional info: What is a enumerable attribute?


If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually.

Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values.

var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
Object.toJSON(data);
//-> '{"name": "Violet", "occupation": "character", "age": 25, "pets": ["frog","rabbit"]}'

http://www.prototypejs.org/api/object/tojson


for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}

I'm still a beginner in JavaScript, but I wrote a small function to recursively print all the properties of an object and its children:

getDescription(object, tabs) {
  var str = "{\n";
  for (var x in object) {
      str += Array(tabs + 2).join("\t") + x + ": ";
      if (typeof object[x] === 'object' && object[x]) {
        str += this.getDescription(object[x], tabs + 1);
      } else {
        str += object[x];
      }
      str += "\n";
  }
  str += Array(tabs + 1).join("\t") + "}";
  return str;
}

Simple JavaScript code:

for(var propertyName in myObject) {
   // propertyName is what you want.
   // You can get the value like this: myObject[propertyName]
}

jQuery:

jQuery.each(obj, function(key, value) {
   // key is what you want.
   // The value is in: value
});