How to find the number of keys in a Javascript variable?

I have a variable as follows:

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

How can I find the length of keyValues? as i need keyValues.length=2.

+4
source share
3 answers

There are several ways to do this. The easiest way 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):

Please note that only keys belonging to the object itself will be counted, not keys in the prototype chain of the object. If you need to count all the keys (including the keys in the prototype chain), just omit the call hasOwnPropertyabove:

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

, , , , , , . ( , ), Object.getOwnPropertyNames() () . , , , , : - , , , , . , !

+5
Object.keys(keyValues).length;
+1

Object.keys(keyValues).length . , . , Object.hasOwnProperty(key).

0

Source: https://habr.com/ru/post/1526251/


All Articles