Converting an object to an array is pretty easy in JavaScript. All we have to do is use Object.keys, or an even easier method to use, Object.entries.

How to convert an object to array in JS

Let’s say we have a simple object that we want to convert to an array:

let tesla = {
    model: "Model 3",
    color: "red",
}

There are a number of ways to do this:

  1. Using Object.keys()
  2. Using Object.entries()

Within the Object.keys() approach, there are also a couple of ways of doing this.

In the first approach, we take the following three steps:

let covertedArr = []; // (1)
let keysArr = Object.keys(tesla); // (2) ["model", "color"];
keysArr.forEach(key => convertedArr.push([key, tesla[key]])); // (3)

convertedArr; // [Array(2), Array(2)]
/* expanded:
0: ["model", "Model 3"]
1: ["color", "red"]
*/

Here’s what each line above does:

  • (1) we set up a convertedArr array to push items into
  • (2) we store the keys of our tesla object in a new keysArr array
  • (3) we run the forEach() method on the keysArr to push keys from keysArr to convertedArr, and values from tesla to convertedArr

A second approach doesn’t require a separate convertedArr; instead, we use the fact that the map() method, when run, returns a brand new array:

let keysArr = Object.keys(tesla); // (1)
let convertedArr = keysArr.map(key => [key, tesla[key]]); // (2)

Here’s what’s each LOC’s doing:

  • (1) we store the keys of our tesla object in the keysArr
  • (2) we run the map() methods on keysArr, mapping each key into an array of two members: a key as the first member, and a tesla[key] as the second member

With Object.entries(), this process of coversion is made significantly more simple:

let arr = Object.entries(tesla);
arr; // [Array(2), Array(2)]
/* expanded:
0: ["model", "Model 3"]
1: ["color", "red"]
*/



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.