Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the number of keys in an object [duplicate]

Tags:

javascript

Possible Duplicate:
How to efficiently count the number of keys/properties of an object in JavaScript?

var values = [{     'SPO2': 222.00000,     'VitalGroupID': 1152,     'Temperature': 36.6666666666667,     'DateTimeTaken': '/Date(1301494335000-0400)/',     'UserID': 1,     'Height': 182.88,     'UserName': null,     'BloodPressureDiastolic': 80,     'Weight': 100909.090909091,     'TemperatureMethod': 'Oral',     'Resprate': null,     'HeartRate': 111,     'BloodPressurePosition': 'Standing',     'VitalSite': 'Popliteal',     'VitalID': 1135,     'Laterality': 'Right',     'HeartRateRegularity': 'Regular',     'HeadCircumference': '',     'BloodPressureSystolic': 120,     'CuffSize': 'XL' }];  for (i=0; i < values.length; i++) {         alert(values.length) // gives me 2.  

How can find how many keys my object has?

like image 872
John Cooper Avatar asked Jul 17 '11 11:07

John Cooper


People also ask

How do you find the number of keys in an object?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.

Can object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do I get a list of keys from an object?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


2 Answers

var value = {     'SPO2': 222.00000,     'VitalGroupID': 1152,     'Temperature': 36.6666666666667,     'DateTimeTaken': '/Date(1301494335000-0400)/',     'UserID': 1,     'Height': 182.88,     'UserName': null,     'BloodPressureDiastolic': 80,     'Weight': 100909.090909091,     'TemperatureMethod': 'Oral',     'Resprate': null,     'HeartRate': 111,     'BloodPressurePosition': 'Standing',     'VitalSite': 'Popliteal',     'VitalID': 1135,     'Laterality': 'Right',     'HeartRateRegularity': 'Regular',     'HeadCircumference': '',     'BloodPressureSystolic': 120,     'CuffSize': 'XL' };  alert(Object.keys(value).length); 
like image 78
Petar Ivanov Avatar answered Sep 21 '22 05:09

Petar Ivanov


try

Object.keys(values).length 

see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys

for compatiblity

if(!Object.keys) Object.keys = function(o){  if (o !== Object(o))       throw new TypeError('Object.keys called on non-object');  var ret=[],p;  for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);  return ret; } 

or use:

function numKeys(o){ var i=0; for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)){ i++}; return i; } 
like image 40
beardhatcode Avatar answered Sep 20 '22 05:09

beardhatcode