How to get length of Javascript Object

Share Button

Introduction :

There is no direct method to find length of an javascript object so I have created a method by which we can get length of javascript object. Use following method to get the length of javascript object.

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

// Get the size of an object
var size = Object.size(myArray);

There’s a sort of convention in JavaScript that you don’t add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.

This solution is inspired from stackoverflow

Share Button