Get Length of JavaScript Object Array

Posted on
By Addam Driver

Unlike javaScript arrays, the “.length” property doesn’t exist in objects. Why? because it’s an object of data. Just a place to store stuff. So here’s a small and simple script you can run to return the length of an object so you can sift through it.

Enjoy!

function getObjectSize(obj) {
var size = 0, key; // get the size data
for (key in obj) { // check the okeys in the object
if (obj.hasOwnProperty(key)) size++; // increase the size
}
return size; // return the size of the object
}


var myObject = {“name”:”Addam”; “date”:”11/23/2011″};
var myObjectSize = getObjectSize(myObject);

The variable “myObjectSize” will return “2″ as there are 2 items in the object.

Happy Coding!

Tags: , , , , , , , ,

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CSS Methods

HTML Goodies

JavaScript

mustache

node.js

The HTML Writers Guild IWA