Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object length [duplicate]

Is there any built-in function that can return the length of an object?

For example, I have a = { 'a':1,'b':2,'c':3 } which should return 3. If I use a.length it returns undefined.

It could be a simple loop function, but I'd like to know if there's a built-in function?

There is a related question (Length of a JSON object) - in the chosen answer the user advises to transform object into an array, which is not pretty comfortable for my task.

like image 293
Larry Cinnabar Avatar asked Apr 03 '11 23:04

Larry Cinnabar


People also ask

Can you get length of object?

You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.

What returns the length of an object?

keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object.

Can object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


1 Answers

For browsers supporting Object.keys() you can simply do:

Object.keys(a).length; 

Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:

var count = 0; var i;  for (i in a) {     if (a.hasOwnProperty(i)) {         count++;     } } 

The hasOwnProperty is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.

like image 175
David Tang Avatar answered Sep 18 '22 18:09

David Tang