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?

Community
  • 1
  • 1
rsk82
  • 28,217
  • 50
  • 150
  • 240
  • From the duplicate question, a useful answer that's not here. Use underscore's size, _.size(). http://stackoverflow.com/a/11346637/1684480 – Thaddeus Albers Sep 07 '13 at 06:19

2 Answers2

83

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.

qiao
  • 17,941
  • 6
  • 57
  • 46
1
var count = 0;
for ( property in hash_table ) count++;
simonecampora
  • 397
  • 2
  • 8
  • 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. – Felix Kling Jan 02 '12 at 15:14
  • thanks for your feedbacK: I have edited my answer accordingly! – simonecampora Jan 02 '12 at 15:18
  • 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. – Felix Kling Jan 02 '12 at 16:04
  • please find more detailes here: http://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 – simonecampora Jan 02 '12 at 16:34