[javascript] Length of a JavaScript object

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

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

This question is related to javascript javascript-objects

The answer is


Like most JavaScript problems, there are many solutions. You could extend the Object that for better or worse works like many other languages' Dictionary (+ first class citizens). Nothing wrong with that, but another option is to construct a new Object that meets your specific needs.

function uberject(obj){
    this._count = 0;
    for(var param in obj){
        this[param] = obj[param];
        this._count++;
    }
}

uberject.prototype.getLength = function(){
    return this._count;
};

var foo = new uberject({bar:123,baz:456});
alert(foo.getLength());

If you are using AngularJS 1.x you can do things the AngularJS way by creating a filter and using the code from any of the other examples such as the following:

// Count the elements in an object
app.filter('lengthOfObject', function() {
  return function( obj ) {
    var size = 0, key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) size++;
    }
   return size;
 }
})

Usage

In your controller:

$scope.filterResult = $filter('lengthOfObject')($scope.object)

Or in your view:

<any ng-expression="object | lengthOfObject"></any>

Use Object.keys(myObject).length to get the length of object/array

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

console.log(Object.keys(myObject).length); //3
_x000D_
_x000D_
_x000D_


For some cases it is better to just store the size in a separate variable. Especially, if you're adding to the array by one element in one place and can easily increment the size. It would obviously work much faster if you need to check the size often.


Simple one liner:

_x000D_
_x000D_
console.log(Object.values({id:"1",age:23,role_number:90}).length);
_x000D_
_x000D_
_x000D_


We can find the length of Object by using:

_x000D_
_x000D_
const myObject = {};
console.log(Object.values(myObject).length);
_x000D_
_x000D_
_x000D_


I had a similar need to calculate the bandwidth used by objects received over a websocket. Simply finding the length of the Stringified object was enough for me.

websocket.on('message', data => {
    dataPerSecond += JSON.stringify(data).length;
}

With the ECMAScript 6 in-built Reflect object, you can easily count the properties of an object:

Reflect.ownKeys(targetObject).length

It will give you the length of the target object's own properties (important).

Reflect.ownKeys(target)

Returns an array of the target object's own (not inherited) property keys.

Now, what does that mean? To explain this, let's see this example.

function Person(name, age){
  this.name = name;
  this.age = age;
}

Person.prototype.getIntro= function() {
  return `${this.name} is ${this.age} years old!!`
}

let student = new Person('Anuj', 11);

console.log(Reflect.ownKeys(student).length) // 2
console.log(student.getIntro()) // Anuj is 11 years old!!

You can see here, it returned only its own properties while the object is still inheriting the property from its parent.

For more information, refer this: Reflect API


If we have the hash

hash = {"a" : "b", "c": "d"};

we can get the length using the length of the keys which is the length of the hash:

keys(hash).length


_x000D_
_x000D_
var myObject = new Object();_x000D_
myObject["firstname"] = "Gareth";_x000D_
myObject["lastname"] = "Simpson";_x000D_
myObject["age"] = 21;_x000D_
_x000D_
var size = JSON.stringify(myObject).length;_x000D_
_x000D_
document.write(size);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
JSON.stringify(myObject)
_x000D_
_x000D_
_x000D_


Here is a completely different solution that will only work in more modern browsers (Internet Explorer 9+, Chrome, Firefox 4+, Opera 11.60+, and Safari 5.1+)

See this jsFiddle.

Setup your associative array class

/**
 * @constructor
 */
AssociativeArray = function () {};

// Make the length property work
Object.defineProperty(AssociativeArray.prototype, "length", {
    get: function () {
        var count = 0;
        for (var key in this) {
            if (this.hasOwnProperty(key))
                count++;
        }
        return count;
    }
});

Now you can use this code as follows...

var a1 = new AssociativeArray();
a1["prop1"] = "test";
a1["prop2"] = 1234;
a1["prop3"] = "something else";
alert("Length of array is " + a1.length);

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

console.log(Object.keys(myObject).length)

// o/p 3

To not mess with the prototype or other code, you could build and extend your own object:

function Hash(){
    var length=0;
    this.add = function(key, val){
         if(this[key] == undefined)
         {
           length++;
         }
         this[key]=val;
    }; 
    this.length = function(){
        return length;
    };
}

myArray = new Hash();
myArray.add("lastname", "Simpson");
myArray.add("age", 21);
alert(myArray.length()); // will alert 2

If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.

Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)


var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
  1. Object.values(myObject).length
  2. Object.entries(myObject).length
  3. Object.keys(myObject).length

The simplest way is like this:

Object.keys(myobject).length

Where myobject is the object of what you want the length of.


A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:

Object.defineProperty(Object.prototype, "length", {
    get: function () {
        return Object.keys(this).length;
    }
});

And you can just use it like so:

var myObj = { 'key': 'value' };
myObj.length;

It would give 1.


A variation on some of the above is:

var objLength = function(obj){    
    var key,len=0;
    for(key in obj){
        len += Number( obj.hasOwnProperty(key) );
    }
    return len;
};

It is a bit more elegant way to integrate hasOwnProp.


Here's the most cross-browser solution.

This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.

if (!Object.keys) {
    Object.keys = function (obj) {
        var arr = [],
            key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                arr.push(key);
            }
        }
        return arr;
    };
}

Object.keys(obj).length;

What about something like this --

function keyValuePairs() {
    this.length = 0;
    function add(key, value) { this[key] = value; this.length++; }
    function remove(key) { if (this.hasOwnProperty(key)) { delete this[key]; this.length--; }}
}

You can always do Object.getOwnPropertyNames(myObject).length to get the same result as [].length would give for normal array.


_x000D_
_x000D_
   let myobject= {}
    let isempty =  !!Object.values(myobject);
    console.log(isempty);
_x000D_
_x000D_
_x000D_


@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".

And in fairness to @palmsey he was quite correct. They aren't associative arrays; they're definitely objects :) - doing the job of an associative array. But as regards to the wider point, you definitely seem to have the right of it according to this rather fine article I found:

JavaScript “Associative Arrays” Considered Harmful

But according to all this, the accepted answer itself is bad practice?

Specify a prototype size() function for Object

If anything else has been added to Object .prototype, then the suggested code will fail:

<script type="text/javascript">
Object.prototype.size = function () {
  var len = this.length ? --this.length : -1;
    for (var k in this)
      len++;
  return len;
}
Object.prototype.size2 = function () {
  var len = this.length ? --this.length : -1;
    for (var k in this)
      len++;
  return len;
}
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
alert("age is " + myArray["age"]);
alert("length is " + myArray.size());
</script>

I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion, surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.


Below is a version of James Coglan's answer in CoffeeScript for those who have abandoned straight JavaScript :)

Object.size = (obj) ->
  size = 0
  size++ for own key of obj
  size

_x000D_
_x000D_
<script>_x000D_
myObj = {"key1" : "Hello", "key2" : "Goodbye"};_x000D_
var size = Object.keys(myObj).length;_x000D_
console.log(size);_x000D_
</script>_x000D_
_x000D_
<p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>
_x000D_
_x000D_
_x000D_

This works for me:

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

Property

Object.defineProperty(Object.prototype, 'length', {
    get: function () {
        var size = 0, key;
        for (key in this)
            if (this.hasOwnProperty(key))
                size++;
        return size;
    }
});

Use

var o = {a: 1, b: 2, c: 3};
alert(o.length); // <-- 3
o['foo'] = 123;
alert(o.length); // <-- 4

If you don't care about supporting Internet Explorer 8 or lower, you can easily get the number of properties in an object by applying the following two steps:

  1. Run either Object.keys() to get an array that contains the names of only those properties that are enumerable or Object.getOwnPropertyNames() if you want to also include the names of properties that are not enumerable.
  2. Get the .length property of that array.

If you need to do this more than once, you could wrap this logic in a function:

function size(obj, enumerablesOnly) {
    return enumerablesOnly === false ?
        Object.getOwnPropertyNames(obj).length :
        Object.keys(obj).length;
}

How to use this particular function:

var myObj = Object.create({}, {
    getFoo: {},
    setFoo: {}
});
myObj.Foo = 12;

var myArr = [1,2,5,4,8,15];

console.log(size(myObj));        // Output : 1
console.log(size(myObj, true));  // Output : 1
console.log(size(myObj, false)); // Output : 3
console.log(size(myArr));        // Output : 6
console.log(size(myArr, true));  // Output : 6
console.log(size(myArr, false)); // Output : 7

See also this Fiddle for a demo.


The solution work for many cases and cross browser:

Code

var getTotal = function(collection) {

    var length = collection['length'];
    var isArrayObject =  typeof length == 'number' && length >= 0 && length <= Math.pow(2,53) - 1; // Number.MAX_SAFE_INTEGER

    if(isArrayObject) {
        return collection['length'];
    }

    i= 0;
    for(var key in collection) {
        if (collection.hasOwnProperty(key)) {
            i++;
        }
    }

    return i;
};

Data Examples:

// case 1
var a = new Object();
a["firstname"] = "Gareth";
a["lastname"] = "Simpson";
a["age"] = 21;

//case 2
var b = [1,2,3];

// case 3
var c = {};
c[0] = 1;
c.two = 2;

Usage

getLength(a); // 3
getLength(b); // 3
getLength(c); // 2

Use:

_x000D_
_x000D_
var myArray = new Object();_x000D_
myArray["firstname"] = "Gareth";_x000D_
myArray["lastname"] = "Simpson";_x000D_
myArray["age"] = 21;_x000D_
obj = Object.keys(myArray).length;_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_


Object.keys does not return the right result in case of object inheritance. To properly count object properties, including inherited ones, use for-in. For example, by the following function (related question):

var objLength = (o,i=0) => { for(p in o) i++; return i }

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

var child = Object.create(myObject);
child["sex"] = "male";

var objLength = (o,i=0) => { for(p in o) i++; return i }

console.log("Object.keys(myObject):", Object.keys(myObject).length, "(OK)");
console.log("Object.keys(child)   :", Object.keys(child).length, "(wrong)");
console.log("objLength(child)     :", objLength(child), "(OK)");
_x000D_
_x000D_
_x000D_


Simple solution:

  var myObject = {};      // ... your object goes here.

  var length = 0;

  for (var property in myObject) {
    if (myObject.hasOwnProperty(property)){
      length += 1;
    }
  };

  console.log(length);    // logs 0 in my example.

Updated: If you're using Underscore.js (recommended, it's lightweight!), then you can just do

_.size({one : 1, two : 2, three : 3});
=> 3

If not, and you don't want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:

$.assocArraySize = function(obj) {
    // http://stackoverflow.com/a/6700/11236
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

Simply use this to get the length:

Object.keys(myObject).length

This method gets all your object's property names in an array, so you can get the length of that array which is equal to your object's keys' length.

Object.getOwnPropertyNames({"hi":"Hi","msg":"Message"}).length; // => 2

If you need an associative data structure that exposes its size, better use a map instead of an object.

_x000D_
_x000D_
const myMap = new Map();

myMap.set("firstname", "Gareth");
myMap.set("lastname", "Simpson");
myMap.set("age", 21);

console.log(myMap.size); // 3
_x000D_
_x000D_
_x000D_


If you know you don't have to worry about hasOwnProperty checks, you can do this very simply:

Object.keys(myArray).length

I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:

var element_count = 0;
for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }

@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".


Here's a different version of James Cogan's answer. Instead of passing an argument, just prototype out the Object class and make the code cleaner.

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

var x = {
    one: 1,
    two: 2,
    three: 3
};

x.size() === 3;

jsfiddle example: http://jsfiddle.net/qar4j/1/


You can simply use Object.keys(obj).length on any object to get its length. Object.keys returns an array containing all of the object keys (properties) which can come in handy for finding the length of that object using the length of the corresponding array. You can even write a function for this. Let's get creative and write a method for it as well (along with a more convienient getter property):

_x000D_
_x000D_
function objLength(obj)_x000D_
{_x000D_
  return Object.keys(obj).length;_x000D_
}_x000D_
_x000D_
console.log(objLength({a:1, b:"summit", c:"nonsense"}));_x000D_
_x000D_
// Works perfectly fine_x000D_
var obj = new Object();_x000D_
obj['fish'] = 30;_x000D_
obj['nullified content'] = null;_x000D_
console.log(objLength(obj));_x000D_
_x000D_
// It also works your way, which is creating it using the Object constructor_x000D_
Object.prototype.getLength = function() {_x000D_
   return Object.keys(this).length;_x000D_
}_x000D_
console.log(obj.getLength());_x000D_
_x000D_
// You can also write it as a method, which is more efficient as done so above_x000D_
_x000D_
Object.defineProperty(Object.prototype, "length", {get:function(){_x000D_
    return Object.keys(this).length;_x000D_
}});_x000D_
console.log(obj.length);_x000D_
_x000D_
// probably the most effictive approach is done so and demonstrated above which sets a getter property called "length" for objects which returns the equivalent value of getLength(this) or this.getLength()
_x000D_
_x000D_
_x000D_


Here's how and don't forget to check that the property is not on the prototype chain:

var element_count = 0;
for(var e in myArray)
    if(myArray.hasOwnProperty(e))
        element_count++;