Javascript Object keys() is a built-in method that returns an array of the given object’s property names in the same order as we get with a standard loop. The Object keys() method is used to return the array whose elements are strings corresponding to the enumerable properties found directly upon the object.
This method is commonly used for iterating over an object’s properties.
Object.keys(obj)
obj(required): An iterable object.
It returns an array of strings representing all the enumerable properties of the given object.
let obj = {
name: 'Jacks',
education: 'IT Engineer',
country : 'USA'
} ;
console.log(Object.keys(obj));
Output
[ 'name', 'education', 'country' ]
So, in the above example, we get an array of object keys.
We can do the same with an array. We can get the array keys as well.
//array
let arr = [
'apple',
'microsoft',
'amazon',
'alphabet',
'tencent',
];
console.log(Object.keys(arr));
Output
[ '0', '1', '2', '3', '4' ]
let object = { 0: "Lion", 1: "Tiger", 2: "Deer" };
console.log(Object.keys(object));
//random key ordering
let object1 = {1: "Tiger", 0: "Lion", 2: "Deer" };
console.log(Object.keys(object1));
Output
[ '0', '1', '2' ]
[ '0', '1', '2' ]
An example of a function property of an object is the Non-enumerable property. Therefore, we will not get the keys to that property.
let myObj = Object.create({}, {
getName: {
value: function () { return this.name; }
}
});
myObj.name = 'krunal';
console.log(Object.keys(myObj));
Output
[ 'name' ]
#javascript #object keys #js #node.js #npm