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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cat = { | |
name : 'foo', | |
age : 12, | |
canRun : function(){ | |
console.log("can run"); | |
} | |
} |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log(Object.getOwnPropertyDescriptor(cat,"canRun")); | |
console.log(Object.getOwnPropertyDescriptor(cat,'name')); |
As you notice besides enumerable, configurable and writable are also set to true.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for (var prop in cat) { | |
console.log(prop); | |
} |
Using the for..in loop, all enumerable properties can be iterated. Above for loop will print all the enumerable properties of cat object.
Leave a Reply