JavaScript Object keys() Method: How to Get Object Keys in JavaScript

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.

Syntax

Object.keys(obj)

Parameters

obj(required): An iterable object.

Return Value

It returns an array of strings representing all the enumerable properties of the given object.

Visual Represenatation

Visual Representation of JavaScript Object keys() Method

Example 1: How to Use Object.keys() Method

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.

Visual Representation of Use of array
//array 
let arr = [
 'apple',
 'microsoft',
 'amazon',
 'alphabet',
 'tencent',
];

console.log(Object.keys(arr));

Output

[ '0', '1', '2', '3', '4' ]

Example 2: Use array-like objects

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' ]

Example 3: Pass the non-enumerable property

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

JavaScript Object keys() Method: How to Get Object Keys in JavaScript
2.00 GEEK