Skip to main content

Archive

Show more

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

how-to-count-number-of-keys-or-properties-of-an-object-in-javascript


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

Answer:

There are several methods to count the keys of a javascript object.


First: using 'for...in'loop.

const rustDetails = { 
 name: 'RustcodeWeb',
 website: 'www.rustcodeweb.com',
 email: 'rustcode95@gmail.com'
};

let count = 0; // counter to count keys
for(let key in rustDetails) {
 count++; // increase the count
}

console.log(count);

Output:

3


Second: but if you javascript object involve in inheritance then use this strict method.

const rustDetails = { 
 name: 'RustcodeWeb',
 website: 'www.rustcodeweb.com',
 email: 'rustcode95@gmail.com'
};

let count = 0; // counter to count keys
for(let key in rustDetails) {
 if (rustDetails.hasOwnProperty(key)) {
   count++; // increase the count
 }
}

console.log(count);

Output:

3


Third: using 'Object.keys()' function.

const rustDetails = { 
 name: 'RustcodeWeb',
 website: 'www.rustcodeweb.com',
 email: 'rustcode95@gmail.com'
};

const result = Object.keys(rustDetails).length;

console.log(result);

Output:

3


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments