Language: EN

javascript-object-keys-values-entries

Keys, Values, and Entries Methods in JavaScript

The methods Object.keys(), Object.values(), and Object.entries() are static methods of the global Object that allow to extract information about the composition of objects.

As we know, we have seen that objects in JavaScript are data structures that allow us to store and organize data in key-value pairs.

With these methods, we can obtain information about the keys, values, and key-value pairs of an object that make up the object, for further manipulation.

  • Object.keys(): Returns an array of keys.
  • Object.values(): Returns an array of values.
  • Object.entries(): Returns an array of key-value pairs.

Usage of the methods

The use of these methods is very simple; we would just call each of them like this,

Object.keys(obj)
Object.values(obj)
Object.entries(obj)
  • obj: The object from which you want to obtain the keys.
  • Order of properties: The methods return the elements in the order in which properties are added to the object (but generally, don’t rely on it)
  • Enumerability: Only enumerable properties appear in the result.

Let’s look at each of them in detail 👇

Object.keys() Method

The Object.keys() method returns an array containing the names of the enumerable properties of an object. The list of keys is returned in the same order as they occur in a for...in loop over the object.

We can see this better with an example. Let’s assume the following object:

const person = {
  name: "Ana",
  age: 25,
  city: "Madrid"
};

To obtain the keys of this object:

const keys = Object.keys(person);

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

Practical examples

Object.values() Method

The Object.values() method returns an array containing the values of the enumerable properties of an object. The order of the values corresponds to the order of the keys.

Continuing with our example, if we use the same person object:

const values = Object.values(person);
console.log(values); // ["Ana", 25, "Madrid"]

Practical examples

Object.entries() Method

The Object.entries() method returns an array of key-value pairs in the form of nested arrays. Each sub-array contains two elements: the property name and its value.

That is, if we apply it to our person example, we would have the following:

const entries = Object.entries(person);

console.log(entries);
// [["name", "Ana"], ["age", 25], ["city", "Madrid"]]

Practical examples