5

I have a variable as follows:

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

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

user3191903
  • 217
  • 2
  • 5
  • 13

3 Answers3

6

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!

Ethan Brown
  • 24,393
  • 2
  • 71
  • 89
2
Object.keys(keyValues).length;
SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
0

Object.keys(keyValues).length will work. But, if it will include inherted properties as well. To get just the object's properties, you need to use Object.hasOwnProperty(key).

nietonfir
  • 4,516
  • 6
  • 27
  • 41
VeeJay
  • 85
  • 4