javascript-object-keys-values-entries

Keys, Values, and Entries Methods in JavaScript

  • 3 min

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

As we know and have seen, 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 that make up an 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.

Using the Methods

Using these methods is very simple, we would simply call each of them like this:

Object.keys(obj)
Object.values(obj)
Object.entries(obj)
Copied!
  • obj: The object from which to obtain the keys.
  • Property Order: The methods return elements in the order properties were added to the object (but in general, don’t rely on that).
  • Enumerable Properties: Only enumerable properties appear in the result.

Let’s look at each one in detail 👇

Object.keys() Method

The Object.keys() method returns an array with 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.

Let’s see it better with an example. Suppose the following object:

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

To get the keys of this object:

const keys = Object.keys(person);

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

Practical Examples

Object.values() Method

The Object.values() method returns an array with the values of the enumerable properties of an object. The order of the values matches the order of the keys.

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

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

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 persona example, we would have the following:

const entries = Object.entries(person);

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

Practical Examples