Skip to content

Convert the object to array JavaScript | Example code

  • by

Use Object.keys() or Object.values() or Object.entries() to convert the object to an array in JavaScript. Consider the below examples to understand these methods.

const zoo = {
  lion: '🦁',
  panda: '🐼',
};

Object.keys(zoo);
// ['lion', 'panda']

Object.values(zoo);
// ['🦁', '🐼']

Object.entries(zoo);
// [ ['lion', '🦁'], ['panda', '🐼'] ]

Note: the Object.keys() method has been available since ECMAScript 2015 or ES6, and Object.values() and Object.entries() have been available since ECMAScript 2017.

Convert the object to an array of JavaScript

A simple example code uses the Object.keys().

It will take properties not values of it.

<!DOCTYPE html>
<html>
<body>

  <script>
    const emp = {
      firstName: 'John',
      lastName: 'Doe'
    };

    const arr = Object.keys(emp);

    console.log(arr);
  </script>

</body>
</html> 

Output:

Convert the object to array JavaScript

To convert property values of the emp object to an array, use the Object.values() method:

<script>
    const emp = {
      firstName: 'John',
      lastName: 'Doe'
    };

    const arr = Object.values(emp);

    console.log(arr);
</script>

Output: [ “John”, “Doe” ]

If you want to convert the enumerable string-keyed properties of an object to an array, then use the Object.entries() method. For example:

<script>
    const emp = {
      firstName: 'John',
      lastName: 'Doe'
    };

    const arr = Object.entries(emp);

    console.log(arr);
</script>

Output:

0: Array [ "firstName", "John" ]
​
1: Array [ "lastName", "Doe" ]

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Answer: You can use Object.keys() and map() to do this

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key), obj[key]]);

console.log(result);

Output:

0: Array [ 1, 5 ]

1: Array [ 2, 7 ]

2: Array [ 3, 0 ]

3: Array [ 4, 0 ]
​
4: Array [ 5, 0 ]
​
5: Array [ 6, 0 ]
​
6: Array [ 7, 0 ]
​
7: Array [ 8, 0 ]
​
8: Array [ 9, 0 ]
​
9: Array [ 10, 0 ]
​
10: Array [ 11, 0 ]
​
11: Array [ 12, 0 ]

Comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading