While working with JavaScript, I come across a requirement to count a number of properties in a JavaScript object. I found two ways to find the number of properties in an object. They are as follows:
- Using for loop
- Using Object.keys
Consider an object, “cat”, as demonstrated 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: 9 | |
} |
You can find a number of properties by iterating in a for loop and update counter, as shown in the below listing:
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
let count = 0; | |
for (var c in cat) { | |
count = count + 1; | |
} | |
console.log(count);// 2 |
Above code will print “2” as output.
The above approach not only prints the object’s own enumerable properties, but it also prints properties of objects to chich it is linked. To further understand it, let us consider listing:
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 animal = { | |
canRun: true | |
} | |
var cat = { | |
name: 'foo', | |
age: 9 | |
} | |
cat.__proto__ = animal; |
There are two objects, cat and animal, and the cat object is linked to an animal object using __proto__ property. Now, when you use for loop to iterate and count a number of properties, it will also count enumerable properties of the animal object. Therefore, the code listing below will print “3”.
Leave a Reply