0

Is there any method to count number of properties (or size) of an object (don't want to use any loop) ?

Suppose i have an object obj as,

obj={id:'0A12',name:'nishant',phone:'mobile'};

Then is there any method which results 3 in this case ?

schnill
  • 805
  • 1
  • 5
  • 11

3 Answers3

6

Object.keys returns an array containing the names of the object's own enumerable properties, so:

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

Note that there may well be a loop involved (within Object.keys), but at least it's within the JavaScript engine. Object.keys was added by ES5, so older browsers may not have it (it can be "shimmed," though; search for "es5 shim" for options).

Note that that's not quite the same list of properties that for-in iterates, as for-in includes properties inherited from the prototype.

I don't believe there's any way to get a list of the object's non-enumerable properties (that would be the point of them!).

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
2

You can use Object.keys() in modern browsers

Object.keys(obj).length
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
-1

You can use

Object.keys(obj).length;

P.S. Only in modern browsers.

Murtaza Khursheed Hussain
  • 14,714
  • 7
  • 52
  • 78