| by Arround The Web | No comments

Getting JavaScript Object key List

Getting the list of keys of an object is a fundamental operation when working with JavaScript objects. There are many situations where developers need to get the list of keys, such as to check if a particular property exists in an object, to access a property of an object dynamically, to iterate over all the properties of an object, and so on.

This post will describe the methods to get the key list of an object.

How to Get the JavaScript Object key List?

For getting the list of keys of an object, use the following methods:

Method 1: Getting JavaScript Object key List Using “Object.keys()” Method

Use the JavaScript pre-built “Object.keys()” method to get the list of keys of the object. This method gives an array of all the enumerable property names (keys) of a given object.

Syntax
Use the following syntax for the Object.keys() method:

Object.keys(object)

Example
Create an object named “obj” with three properties and their respective values:

const obj = {
 alpha: '25',
 beta: '72',
 gamma: '15'
};

Call the “Object.keys()” method to get the list of the keys of an object and store it in a variable “objKeyList”:

const objKeyList = Object.keys(obj);

Print the list of the keys of an object on the console:

console.log(objKeyList);

The output displays the array of keys of an object:

Method 2: Getting JavaScript Object key List Using “for-in” Loop with “push()” Method

You can also use the “for-in” loop to iterate the keys in an object and push the keys to an empty array using the “push()” method.

Example
Create an empty array named “objKeyList”:

var objKeyList = [];

Iterate the object using the “for-in” loop and push keys in an empty array with the help of the “push()” method:

for (var keys in obj){
 objKeyList.push(keys);
}

Finally, print the array on the console:

console.log(objKeyList);

Output

We have compiled all the essential information relevant to getting the list of keys of an object in JavaScript.

Conclusion

For getting the list of keys of an object, use the JavaScript pre-built “Object.keys()” method or the “for-in” loop with the “push()” method. The Object.keys() method gives an array of keys of the object. The for-in loop iterates the array keys and pushes them into an empty array. This post described the methods to get the key list of an object.

Share Button

Source: linuxhint.com

Leave a Reply