To count the numbers of keys or properties in an object in JavaScript First, we can use the Object.keys()
method to extract the keys from an object into an array and then use the length
property on that array returned from the Object.keys()
method to get the total count.
const count = Object.keys(obj).length;
Consider this object with some properties,
// an object
const obj = {
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "[email protected]",
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
name: "Romaguera-Crona",
catchPhrase: "Multi-layered client-server neural-net",
bs: "harness real-time e-markets",
},
};
First let's make an array from the object's keys
or properties
by passing obj
as an argument to the Object.keys()
method like this,
// an object
const obj = {
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "[email protected]",
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
name: "Romaguera-Crona",
catchPhrase: "Multi-layered client-server neural-net",
bs: "harness real-time e-markets",
},
};
// make the object's keys or properties
// into an array using Object.keys() method
const keysArr = Object.keys(obj);
Now, all we need is to do is to get the length
property from the keysArr
to get the total number of keys or properties present in the object.
It can be done like this,
// an object
const obj = {
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "[email protected]",
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
name: "Romaguera-Crona",
catchPhrase: "Multi-layered client-server neural-net",
bs: "harness real-time e-markets",
},
};
// make the object's keys or properties
// into an array using Object.keys() method
const keysArr = Object.keys(obj);
// get the total number of keys
// using the length property in the keysArr
console.log(keysArr.length); // 7
See this example live in JSBin.