Getting JavaScript Object key List
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:
Example
Create an object named “obj” with three properties and their respective values:
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”:
Print the list of the keys of an object on the console:
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”:
Iterate the object using the “for-in” loop and push keys in an empty array with the help of the “push()” method:
objKeyList.push(keys);
}
Finally, print the array on the console:
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.
Source: linuxhint.com