46

Possible Duplicate:
Length of Javascript Associative Array

hash_table = {a: 131, b: 222, c:313} 

The length method is not working of course since it will be confused with a key.

So how do I do it?

1

2 Answers 2

85

Object.keys will return all the keys in the object as a list, then use length to get the length.

example:

Object.keys(hash_table).length 

NOTE that this is ECMA 5 and may not be available in some browsers. see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys for full document.

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

4 Comments

Would it return also inherited properties ?
Nope, it will return only own properties.
As I understand it, Object.keys is not supported in IE8 and lower, so beware...
Always supported in 2017 :)
1
var count = 0; for ( property in hash_table ) count++; 

4 Comments

JSON is a data exchange format and has nothing to do with JavaScript, besides the name and similar syntax. JavaScript does not have "Associative Arrays", only arrays.
thanks for your feedbacK: I have edited my answer accordingly!
Still, what do you mean by "using Arrays in associative fashion"? The length property is only updated for numerical properties,i.e. arr[0] = 42.. Non-numerical properties do not update length and should not be used for arrays as it is just confusing.
please find more detailes here: en.wikipedia.org/wiki/JavaScript_syntax#Array "One can use the object declaration literal to create objects that behave much like associative arrays" but indeed I was wrong. I will edit my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.