Search code snippets, questions, articles...

Get number of keys in an object Javascript

In this article, we are going to explain the code examples that can be used to get the number of keys from an object using Javascript.
const my_object = {"name": "Rick", "occupation": "Engineer", "city": "Atlanta"};

const number_of_keys = Object.keys(my_object).length;

console.log(number_of_keys);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

3

Try it yourself

An object is a collection of items in Javascript that stores the data in key-value pair format. If you working with objects in Javascript and have multiple keys that have some values and you want to the count of keys that the object have then you can use the code examples described in this post.

Get the number of keys from an object using Object.keys() and length

The Object.keys() function of Javascript returns an array that contains all the keys of an object. As we know that we can use .length to get the length of the array. So we can use them combined to get the number of keys from the object.

Syntax

Object.keys(object_name).length

Code Example

const num_object = {
    "1": "a",
    "2": "b",
    "3": "c",
    "4": "d" 
};

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

console.log(result);

Output

4

Try it yourself

Get the number of keys in an Object using For Loop

A for loop is a type of looping statement that allows you to run a set of statements a fixed number of times.

The for loop has three parts:

1. The initialization where you initialize the loop counter.

2. The condition where you specify the condition that must be true for the loop to run.

3. The increment where you specify how the loop counter should be updated each time the loop runs.

To use a for loop to get the number of keys in an object, you would initialize a variable and will increase it by 1 in each iteration.

Code Example

const num_object = {
    "1": "a",
    "2": "b",
    "3": "c",
    "4": "d" 
};

let result = 0;
for (let k in num_object) {
    result++
}

console.log(result)

Output

4

Live Demo of the above code

Was this helpful?
0 Comments