Hi Friends 👋,
Welcome To Infinitbility! ❤️
Today, we are going to learn How to get a number of keys of objects in javascript, here we will use the keys()
method and array length to get a number of keys.
Basically, The keys()
method creates an array of object keys, and when we got an array we will use simple array length syntax to get a number of keys.
Well, let’s start today’s tutorial How to get the number of keys of the object in javascript?
Here, we will do
- create a sample object variable
- use
Object.keys()
method to get an array - use
.length
to get the number of keys
// create sampel oject variable
let sampleObject = {
id: 1,
name: "infinitbility",
domain: "infinitbility.github.io",
email: "infinitbility@gmail.com"
};
// convert keys to array
let sampleObjectKeys = Object.keys(sampleObject);
console.log("sampleObjectKeys", sampleObjectKeys)
// print number of keys
console.log("number of keys", sampleObjectKeys.length);
we can also write in one line like the below example.
console.log(Object.keys(sampleObject).length);
lets run it, it should show 4
number of keys.
Output
All the best 👍.