How To Quickly Get An Object’s Keys As Array In JavaScript

Get an Object’s Keys as Array in JavaScript

Array and object are two common data types in JS, so there are a bunch of built-in functions to work with these two data types. In this case, to quickly get an object’s keys as array in JavaScript, we will use three of them. Read to the end to discover the three functions.

How to get an object’s keys as array in JavaScript?

In JS, objects cannot be iterated with a regular loop but must use specialized functions for working with objects. Therefore, to get an object’s keys as an array in JavaScript, we use the following methods:

Using Object.keys() method

Syntax:

Object.keys(obj)

Parameters:

  • obj: An object that you want to get all property.

Object.keys() returns an array including the property names of a given object.

We can use object.keys() to solve our problem like this:

const post = {
	title: "Get an Object's Keys as Array in JS",
	author: 'learnshareit',
	publicDate: '10/05/2022'
};

const keyArr = Object.keys(post);
console.log(keyArr);

Output:

["title", "author", "publicDate"]

Using for … in.

Syntax:

for (variable in object) {
    // Do something
}

Parameters:

  • variable: Get the object’s key at each iteration.
  • object: Any object is iterated over.

In this case, we will use for...in loop to iterate over the elements of the object and use the push() function to push the object’s key into an empty array at each loop. Like this:

const post = {
	title: "Get an Object's Keys as Array in JS",
	author: 'learnshareit',
	publicDate: '10/05/2022'
};

const keyArr = [];

for (let key in post) {
	keyArr.push(key); // Push the key into the 'keyArr' array
}

console.log(keyArr);

Output:

["title", "author", "publicDate"]

Using Object.entries() method

Syntax:

Object.entries(obj)

Parameters:

  • obj: Any object is iterated over to return [property, value] pairs.

Object.entries() returns an array whose elements are an array contains the {property, value} pairs of the object. The order of the elements in the array is the same as the order of the keys in the object. We can iterate over the return of Object.entries() with the forEach() method and easily get the keys of the object in the same way as above.

const post = {
	title: "Get an Object's Keys as Array in JS",
	author: 'learnshareit',
	publicDate: '10/05/2022'
};

let entries = Object.entries(post);
let keyArr = [];

entries.forEach((entry) => {
	keyArr.push(entry[0]); // entry = [key, value] -> entry[0] = key
});

console.log(keyArr);

Output:

["title", "author", "publicDate"]

Summary

Congratulations, we have reached the end of this article. We believe that next time you can get an object’s keys as array in JavaScript easily. If there are any topics you have not solved, please comment below, and we will help you. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *