Convert object to array in Javascript

Object.entries() have been available since ECMAScript 2017. This method returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon object
const colors = { 1: 'Red', 2: 'Blue', 3: 'Green' }; const cls = Object.entries(colors); console.log(cls);
[ [ '1', 'Red' ], [ '2', 'Blue' ], [ '3', 'Green' ] ]

Object.keys

Object.keys method returns a new array which consists of all the keys in sequential order.
const colors = { 1: 'Red', 2: 'Blue', 3: 'Green' }; const keys = Object.keys(colors); console.log(keys);
[ '1', '2', '3' ]

Object.values

Object.values method returns a new array which consists of all the values in sequential order.
const colors = { 1: 'Red', 2: 'Blue', 3: 'Green' }; const values = Object.values(colors); console.log(values);
['Red', 'Blue', 'Green']

Array.prototype.map()

You can achieve the same result by using map() and Object.keys().
const colors = { 1: 'Red', 2: 'Blue', 3: 'Green' }; var result = Object.keys(colors).map((key) => [Number(key), colors[key]]); console.log(result);
[ [ 1, 'Red' ], [ 2, 'Blue' ], [ 3, 'Green' ] ]
In the above code, Object.keys() returns an array of the given object's own enumerable string-keyed property names and the Array.prototype.map() creates a new array populated with the results of calling a provided function on every element in the calling array.

Destructuring Object.entries()

The destructuring makes it possible to unpack values from arrays. Here Object.entries() each subarray holds an individual key and value separated by a comma. In order to convert this nested array into a plain one-dimensional array, you have to destructure the nested array.
const colors = { 1: 'Red', 2: 'Blue', 3: 'Green' }; let keys = Object.entries(colors); let keyArr = []; keys.forEach(([key, val]) => { keyArr.push(key); keyArr.push(val); }); console.log(keyArr);
[ '1', 'Red', '2', 'Blue', '3', 'Green' ]

JavaScript Earlier Approach - Object to Array


Javascript convert Object to Array
Earlier approach in JavaScript was iterating over the object and pushing the individual object properties into a new array.
const colors = { 1: 'Red', 2: 'Blue', 3: 'Green' }; let keys = []; for (let value in colors) { keys.push(value); } console.log(keys);
[ '1', '2', '3' ]