Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of keys in Javascript variable? [duplicate]

I have a variable as follows:

var keyValues={
  key1:{
  ----------
  },
  key2:{
  ----------
  }
}

How can I find length of keyValues ? like I need keyValues.length=2.

like image 728
user3191903 Avatar asked Feb 10 '14 22:02

user3191903


2 Answers

There are a couple of ways to do this. The easiest is to use Object.keys (documentation):

console.log(Object.keys(keyValues).length);

This is essentially equivalent to:

var count = 0;
for(var key in keyValues){
    if(keyValues.hasOwnProperty(key)) count++;
}
console.log(count):

Note that will only count keys that belong to the object itself, NOT keys on the object's prototype chain. If you need to count all keys (including keys in the prototype chain), just omit the call to hasOwnProperty above:

var count = 0;
for(var key in keyValues){
    count++;
}
console.log('all keys, including prototype chain: ' + count):

Note that these methods will not count properties that aren't marked as enumerable, which is probably exactly what you want. If you do really want to get every last thing (including stuff which is marked as enumerable), you'll have to use Object.getOwnPropertyNames() (documentation) and walk the prototype chain yourself. Like I said, this is probably not what you want: if someone goes to the trouble to make a property non-enumerable, that's because they don't want it enumerated. Just making sure my answer covers all the bases!

like image 51
Ethan Brown Avatar answered Sep 27 '22 21:09

Ethan Brown


Object.keys(keyValues).length;
like image 37
SLaks Avatar answered Sep 27 '22 20:09

SLaks