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 ?
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 ?
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!).
You can use Object.keys() in modern browsers
Object.keys(obj).length
You can use
Object.keys(obj).length;
P.S. Only in modern browsers.