Length of a JavaScript object

If I have a JavaScript object, say

var myObject = new Object();
 myObject[firstname] = Gareth;
 myObject[lastname] = Simpson;
 myObject[age] = 21;
 

is there a built-in or accepted best practice way to get the length of this object?

Text Copied From stackoverflow.com
on : Thu, Aug 07, 2008 Views : 1193612

Accepted Answer

The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:

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.


Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

var size = Object.keys(myObj).length;
 

This doesn't have to modify any existing prototype since Object.keys() is now built in.

Text Copied From stackoverflow.com
on : Sat, Aug 09, 2008

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp