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 ?

1

3 Answers 3

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!).

Sign up to request clarification or add additional context in comments.

Comments

2

You can use Object.keys() in modern browsers

Object.keys(obj).length

Comments

-1

You can use

Object.keys(obj).length;

P.S. Only in modern browsers.

2 Comments

just asking..how is this different from @Arun P Johny answer..
Might have been posted before seeing that answer. Shows only 3 min difference between the posts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.