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 array in JavaScript. Consider the below examples to understand the this 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 the Object.values() and Object.entries() have been available since ECMAScript 2017.

Convert the object to array JavaScript

Simple example code use 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 ]

Do 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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.