DEV Community

Cover image for How to count the number of properties or keys in an object in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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;
Enter fullscreen mode Exit fullscreen mode

Consider this object with some properties,

// an object
const obj = {
  id: 1,
  name: "Leanne Graham",
  username: "Bret",
  email: "Sincere@april.biz",
  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",
  },
};
Enter fullscreen mode Exit fullscreen mode

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: "Sincere@april.biz",
  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);
Enter fullscreen mode Exit fullscreen mode

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: "Sincere@april.biz",
  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
Enter fullscreen mode Exit fullscreen mode

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Oldest comments (0)