How to Get Keys of a Javascript Object with Object.keys()

Use-Cases of this Tutorial

  • Know how to get all keys of a Javscript object.
  • Know about the Object.keys() method.

Keys of a Javscript object can be retrieved using the Object.keys() method.

Object.keys()

The Object.keys() method returns a given object's own enumerable property names as an array.

  1. An enumerable property of an object is basically "countable". This property has its "enumerable" attribute set to "true". If set to "false" it becomes non-enumerable.
  2. Own enumerable properties are those enumerable properties of the object that are owned by the object itself and not inherited through its prototype chain.

For simple objects we don't need to worry about enumerable. Basically Object.keys() method returns an array holding all keys of the object.

Example #1 :

var person = {
	name: "John Doe",
	age: 27,
	gender: "M"
};

var keys = Object.keys(person);

// [ "name", "age", "gender" ]
console.log(keys);

Example #2 :

// creating objects using constructor function
function Person(name, age, gender) {
	this.name = name;
	this.age = age;
	this.gender = gender;
}

Person.prototype = {
	city: "Paris",
	country: "France"
};

// create new object
var person1 = new Person("John Doe", 27, "M");

var keys = Object.keys(person1);

console.log(keys);

// [ "name", "age", "gender" ]
// "city" and "country" will not be included as the belong to the prototype chain
Loading Comments