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.
In this example, we use Object.keys()
method to convert keys of the object
into array
.
xxxxxxxxxx
1
const object = {
2
1: 'a',
3
2: 'b',
4
3: 'c',
5
};
6
7
const array = Object.keys(object);
8
9
console.log(JSON.stringify(array)); // [ '1', '2', '3' ]
In this example, we use Object.values()
method to convert values of the object
into array
.
xxxxxxxxxx
1
const object = {
2
1: 'a',
3
2: 'b',
4
3: 'c',
5
};
6
7
const array = Object.values(object);
8
9
console.log(JSON.stringify(array)); // [ 'a', 'b', 'c' ]
In this example, we use Object.entries()
method to convert enumerable string-keyed properties [key, value] pairs of the object
into array
.
xxxxxxxxxx
1
const object = {
2
1: 'a',
3
2: 'b',
4
3: 'c',
5
};
6
7
const array = Object.entries(object);
8
9
console.log(JSON.stringify(array)); // [ [ '1', 'a' ], [ '2', 'b' ], [ '3', 'c' ] ]