Convert an Object to an Array using JavaScript

avatar

Borislav Hadzhiev

Sun Oct 31 20212 min read

banner

Photo by Chema Photo

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. Foe 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee