Convert a JavaScript object to an array

Hello Programmers, In this tutorial, you will learn how to convert a JavaScript object to an array. There are different inbuilt functions already defined in JavaScript to do so. There are explained below –

Object.keys()

Object.keys() method returns an array that consists of all the enumerable keys of the object. Below is a code snippet explaining the same.

const pokemon = {
    name: "Pikachu",
    move: "Volt Tackle",
};
const arr = Object.keys(pokemon);
console.log(arr);
Output : [ 'name', 'move' ]

Here we have an object named pokemon. It has two key-value pairs. We have used Object.keys() method on the object and the keys are stored in our array.

Object.values()

Object.values() is similar to Object.keys() method only difference is it returns an array that consists of all the corresponding values of each key in the object. Following is an example code snippet.

const pokemon = {
    name: "Pikachu",
    move: "Volt Tackle",
};
const arr = Object.values(pokemon);
console.log(arr);
Output : [ 'Pikachu', 'Volt Tackle' ]

Object.entries()

Object.entries() returns an array of array containing keys and value pairs. Take a look at the following code.

const pokemon = {
    name: "Pikachu",
    move: "Volt Tackle",
};
const arr = Object.entries(pokemon);
console.log(arr);
Output : [ [ 'name', 'Pikachu' ], [ 'move', 'Volt Tackle' ] ]

In the above code snippet, we get an array of arrays. If we look at the first array it contains 2 elements which are the key and the value of the object.

So there are three different methods that allow us to convert JS objects into an array. We can do the same thing manually by declaring an array and pushing elements in it but doing that will cost us a bit of line of code.

You may also read –

Leave a Reply

Your email address will not be published.