Federico
Federico

Reputation: 479

Count properties of JavaScript object

My question is short and concise.

I need count the attributes of Json object, for example

 obj={
      name:'Jhon',
      age:25
 }

This must return 2, one for 'name' and ohter for 'age'. I try use.

 obj.count();
 obj.length();

But nothing...

The all solutions that I found in internet was for count elements of array.

Thanks to all!

Upvotes: 3

Views: 409

Answers (3)

zyglobe
zyglobe

Reputation: 1240

Just to add to the Object.keys(obj).length solution, here's a polyfill for browsers that don't support Object.keys.

Object.keys = Object.keys || function(o,k,r){
    r=[];
    for(k in o){
        r.hasOwnProperty.call(o,k) && r.push(k);
    }
    return r;
}

Upvotes: 2

PSL
PSL

Reputation: 123739

Try Object.keys, There is no built in length property or method on Javascript object.

var propCount = Object.keys(obj).length;

Note that there is a Shim you need to add in your source code for added support for some older browsers (ex: IE < 9) . Read the documentation link from MDN

Upvotes: 11

Norbert Pisz
Norbert Pisz

Reputation: 3440

Try like this:

Object.keys(obj).length

Upvotes: 3

Related Questions