EN
JavaScript - convert object to array
0
points
In this article, we would like to show you how to convert object to array in JavaScript.
To convert an object to an array we can use one of the following methods:
Object.keys()- converts object keys into an array,Object.values()- converts object values into an array,Object.entries()- converts enumerable string-keyed properties [key, value] pairs of an object into an array.
Note:
The
Object.keys()method has been introduced in ES6, and theObject.values()andObject.entries()in ES8.
1. Convert object keys to array
In this example, we use Object.keys() method to convert keys of the object into array.
// ONLINE-RUNNER:browser;
const object = {
1: 'a',
2: 'b',
3: 'c',
};
const array = Object.keys(object);
console.log(JSON.stringify(array)); // [ '1', '2', '3' ]
2. Convert object values to array
In this example, we use Object.values() method to convert values of the object into array.
// ONLINE-RUNNER:browser;
const object = {
1: 'a',
2: 'b',
3: 'c',
};
const array = Object.values(object);
console.log(JSON.stringify(array)); // [ 'a', 'b', 'c' ]
3. Convert object entries (key-value pairs) to array
In this example, we use Object.entries() method to convert enumerable string-keyed properties [key, value] pairs of the object into array.
// ONLINE-RUNNER:browser;
const object = {
1: 'a',
2: 'b',
3: 'c',
};
const array = Object.entries(object);
console.log(JSON.stringify(array)); // [ [ '1', 'a' ], [ '2', 'b' ], [ '3', 'c' ] ]