Convert an Object to an Array using JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 31, 2021

banner

Photo from Unsplash

Convert an Object to an Array in JavaScript #

There are three ways to convert an object to an array:

  1. Object.keys() - returns an array containing the object's keys.
  2. Object.values() - returns an array containing the object's values.
  3. Object.entries() - returns an array containing key-value pair arrays.
index.js
const obj = {country: 'Chile', city: 'Santiago'}; // 👉️ ['country', 'city'] const keys = Object.keys(obj); console.log(keys); // 👉️ ['Chile', 'Santiago'] const values = Object.values(obj); console.log(values); // 👉️ [ ['country', 'Chile'], ['city', 'Santiago'] ] const entries = Object.entries(obj); console.log(entries);

The first example uses the Object.keys method to get an array of the object's keys.

The method returns an array of strings where the keys of the object are in the same order as provided by a for...in loop.

index.js
// 👇️️ ['one', 'two'] console.log(Object.keys({one: 1, two: 2}));

The second example shows how to use the Object.values method to get an array of the object's values.

Similarly to the keys method, the values are added to the array in the same order as that provided by a for...in loop.

index.js
// 👇️️ [1, 2] console.log(Object.values({one: 1, two: 2}));

The third example uses the Object.entries method, which returns a two dimensional array.

The nested arrays consist of 2 elements - the key and the value.

index.js
// 👉️ [ ['one', 1], ['two', 2] ] console.log(Object.entries({one: 1, two: 2}));

There are many applications for these nested arrays that contain key-value pairs. For example, they can be used to create an object, using the Object.fromEntries method.

index.js
const arr = [ ['one', 1], ['two', 2], ]; const obj = Object.fromEntries(arr); console.log(obj); // 👉️ {one: 1, two: 2}

The Object.fromEntries method converts an array of key-value pairs into an object.

Similarly you could also use an array of key-value pairs to create a Map, which is a data structure very similar to the object, where the insertion order of keys is preserved and any value (objects and primitives) can be used as keys or values.

index.js
const arr = [ ['one', 1], ['two', 2], ]; const map = new Map(arr); console.log(map); // 👉️ {'one' => 1, 'two' => 2}

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.