How to Efficiently Count the Number of Keys/Properties of an Object in JavaScript

How to efficiently count the number of keys/properties of an object in JavaScript

To do this in any ES5-compatible environment, such as Node.js, Chrome, Internet Explorer 9+, Firefox 4+, or Safari 5+:

Object.keys(obj).length
  • Browser compatibility
  • Object.keys documentation (includes a method you can add to non-ES5 browsers)

Efficiently counting the number of keys / properties of an Object in JavaScript

See the source, specifically GetLocalElementKeys

v8 objects.cc

Count number of Properties of an Object in a For Loop in JavaScript

counter.length is undefined.

You can use Object.keys() to get all the keys and get the length property form that:

var person = {
name: 'John Potato',
age: 31,
weight: '145kg',
birthday: 'Some day mid July'
}
let counter = Object.keys(person).length;
console.log('The person has ' + counter + ' properties');

Finding the number of keys in an object

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);

count the total number of keys from nested objects and arrays

For the data provided, there are nine (9) keys. You could use a recursive countKeys(t) and do a type analysis on t's type -

  1. When it's an Object, for all v in Object.values(t), reduce and count one plus the recursive result, countKeys(v)
  2. When it's an Array, for all v in t, sum countKeys(v)
  3. Otherwise t is neither an Object nor an Array, return zero

function countKeys(t) {
switch (t?.constructor) {
case Object: // 1
return Object
.values(t)
.reduce((r, v) => r + 1 + countKeys(v), 0)
case Array: // 2
return t
.reduce((r, v) => r + countKeys(v), 0)
default: // 3
return 0
}
}

const data =
{key1:"1",key2:"2",key3:{key4:"4"},key5:[{key6:"6",key7:"7"},{key8:"8",key9:"9"}]}

console.log(countKeys(data))

How do I count a JavaScript object's attributes?

There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

Here's one way:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted

var count = 0;
for (var k in foo) {
if (foo.hasOwnProperty(k)) {
++count;
}
}
alert("Found " + count + " properties specific to foo");

The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

Javascript counting number of objects in object

The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.

Then you can use either _.size(object) or _.keys(object).length

For your obj.Data, you could test this with:

console.log( _.size(obj.Data) );

or:

console.log( _.keys(obj.Data).length );

Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)

Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:

function ObjectLength( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
};

You can test this with:

console.log( ObjectLength(obj.Data) );

That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:

function ObjectLength_Modern( object ) {
return Object.keys(object).length;
}

function ObjectLength_Legacy( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
}

var ObjectLength =
Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;

and as before, test it with:

console.log( ObjectLength(obj.Data) );

This code uses Object.keys(object).length in modern browsers and falls back to counting in a loop for old browsers.

But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.

I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.

Thanks to Barmar for suggesting Object.keys for newer browsers in his answer.

Length of a JavaScript object

Updated answer

Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

var size = Object.keys(myObj).length;

This doesn't have to modify any existing prototype since Object.keys() is now built-in.

Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.

Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.

Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols.

var person = {
[Symbol('name')]: 'John Doe',
[Symbol('age')]: 33,
"occupation": "Programmer"
};

const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1

let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2

How to count and add the values of keys in a object

Here's what your function could look like:

  1. Iterate over all list items
  2. Get the text content of the item
  3. look up the price in the products object by using the text content as key
  4. add to the total
  5. return the total

I used Array.from() and Array.prototype.reduce() to achieve this all in one go. Of course you'd need a distinct class or even better an ID on the list instead of simply selecting all list items on the page.

let products = {

oreos: 20,

milk: 17,

bread: 12,

doritos: 10

}

function getTotal(listElements, productPrices) {

var total = Array.from(listElements).reduce(function(total, listItem) {

total += productPrices[listItem.textContent] || 0;

return total;

}, 0);

return total;

}

console.log(getTotal(document.querySelectorAll('li'), products));
<ul>

<li>oreos</li>

<li>milk</li>

</ul>


Related Topics



Leave a reply



Submit