How to print or enumerate properties of a JavaScript object?

I usually come across the following requirements,

  • How to print name of all the properties of an object?
  • How to print only the methods of an object?
  • How to print even non-enumerable properties of an object?

In this post, we will explore all the options to iterate and print properties of a JavaScript object. Let us consider the object cat, as shown in the listing below:


var cat = {
name : 'foo',
age : 12,
canRun : function(){
console.log("can run");
}
}

view raw

jsobject.js

hosted with ❤ by GitHub

By default, for all properties of an object enumerable is set to true. So right now, if we print description of cat’s canRun and name properties using the Object.getOwnPropertyDescriptor, we will find enumerable value true for the both properties.


console.log(Object.getOwnPropertyDescriptor(cat,"canRun"));
console.log(Object.getOwnPropertyDescriptor(cat,'name'));

view raw

jsobject2.js

hosted with ❤ by GitHub

As you notice besides enumerable, configurable and writable are also set to true.

image

Let us start with printing all properties which enumerable is true.

Printing all enumerable properties using for..in loop

We can print all enumerable properties either own or inherited of cat object using JavaScript for..in loop.


for (var prop in cat) {
console.log(prop);
}

view raw

jsobject3.js

hosted with ❤ by GitHub

Using the for..in loop, all enumerable properties can be iterated. Above for loop will print all the enumerable properties of cat object.

Read full article on the Infragistics blog

Leave a comment

Create a website or blog at WordPress.com