Javascript - object.keys() method example

In this tutorial, we will learn about the javascript object.keys methods. object.keys method is used to return a key as an array of given object's own enumerable property. You can also achieve this with the forEach loop.

Javascript object.keys() example

Get javascript object keys with object.keys() method.

Syntax

Object.keys(obj);

The obj parameter is required. The object.keys method accepts one parameter object which returns enumerable properties of the given object.

Let's take an example:

const obj1 = {
	'currency' : 'dollar',
	'product' : 'Shoe',
	'location': 'Australia'
}

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

The above example will return the array of strings of the given enumerable object obj1

Object.keys can be applied on array as well. Let's take an example

var arr1 = [
	'door', 
	'washing-machine', 
	'bell', 
	'ring'
];
Object.keys(arr1);

The output of the above code will be

0: "0"
1: "1"
2: "2"
3: "3"
length: 4

Non-enumerable properties

We can get the property of an object which is not enumerable. Let's take an example

var mObj = Object.create({}, {
getModel: {
value: function () { return this.model; }
} 
});
mObj.model = 'BMW';
console.log(Object.keys(mObj));

The output of the above code will be

0: "model"
length: 1