4
94

JavaScript: How to Convert Object to Array in JavaScript

Reading Time: 2 minutes

In a situation where we need to use some methods that only take in an array, we can convert Object to Array with 3 methods with JavaScript Object. They are Object.entries(), Object.keys() and Object.values(). These methods are introduced since ES6.

Conversion Prior to ES6

Prior to ES6, the conversion from object to array will require first to create 2 empty arrays where one is for keys and one is for values. Subsequently, we will need to write a for loop to push the keys and values to the result arrays.

Let’s look at the example below.

var person = {
  name: 'my-name',
  age: 11,
};

var keys = [];
var values = [];

for (var key in person) {
  keys.push(key);
  values.push(person[key]);
}

console.log(keys);     // ["name", "age"]
console.log(values);   // ["my-name", 11]

ES6 Methods to Convert Object to Array

With the update over Object as the standard built-in object in ES6 JavaScript, there are 3 new methods that allow us to retrieve the array of keys, values or both from Object easily without actually writing the loop.

  • Object.entries() -> Return keys and values
  • Object.keys() -> Return keys
  • Object.values() -> Return values

Let’s look into them in more detail below.

With Object.entries() Method

Object.entries() method will loop though the object and return a 2 dimensional array containing both the key and value as an array.

const person = {
  name: 'my-name',
  age: 11,
};

const keyValueArray = Object.entries(person);

console.log(keyValueArray);     // [["name", "my-name"], ["age", 11]]

With Object.keys() Method

Object.keys() method will loop though the object and return a new array containing the keys in the original datatype.

const person = {
  name: 'my-name',
  age: 11,
};

const keys = Object.keys(person);

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

With Object.entries() Method

Object.keys() method will loop though the object and return a new array containing the values in the original datatype.

const person = {
  name: 'my-name',
  age: 11,
};

const values = Object.values(person);

console.log(values);     // ["my-name", 11]

Conclusion

As we can see from the examples, converting from object to array has becoming from simple since we do not have to manually write loops and hence, less complexity.

Show Comments

No Responses Yet

Leave a Reply