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
  • 855
  • 1
  • 5
  • 12

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
  • 959,406
  • 173
  • 1,780
  • 1,769
2

You can use Object.keys() in modern browsers

Object.keys(obj).length
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
-1

You can use

Object.keys(obj).length;

P.S. Only in modern browsers.

Murtaza Khursheed Hussain
  • 14,976
  • 7
  • 55
  • 82