3

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!

1
  • 2
    That's not JSON. That's JavaScript. (Specifically, it's a JavaScript object initializer.) JSON is a non-code, textual data format. And in JavaScript they're called "properties," not "attributes" (not a criticism, "attributes" is a general term -- just letting you know what the precise term is). Commented Oct 1, 2013 at 21:08

3 Answers 3

11

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

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

4 Comments

I would advise not to touch Object.prototype, you will be affecting everything else with unpredictable results.
@LexLythius yeah you are right, it is not advisable at all to extend built in prots
yes but there is a shim in MDN which you can add to your source in case not available.
3

Try like this:

Object.keys(obj).length

Comments

2

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;
}

1 Comment

You would need to put return r outside the for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.