Browse By

How to get the size of a javascript Object

There are times that you will need to get the size of an object but the lack of .length maybe will drive you crazy. The solution is simple. Just create a function in which you pass the object as a parameter and then loop through the object keys. With the help of .hasOwnProperty(key) you can increase the value of a counter variable. After the loop you simply return this variable. Have a look at the code below. I find it quite a useful snippet.

Object.size = function (obj) {
	var size = 0, key;
	for (key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

Leave a Reply

Your email address will not be published. Required fields are marked *