Borislav Hadzhiev
Last updated: Oct 31, 2021
Check out my new book
There are three ways to convert an object to an array:
Object.keys()
- returns an array containing the object's keys.Object.values()
- returns an array containing the object's values.Object.entries()
- returns an array containing key-value pair arrays.const obj = {country: 'Chile', city: 'Santiago'}; // 👉️ ['country', 'city'] const keys = Object.keys(obj); console.log(keys); // 👉️ ['Chile', 'Santiago'] const values = Object.values(obj); console.log(values); // 👉️ [ ['country', 'Chile'], ['city', 'Santiago'] ] const entries = Object.entries(obj); console.log(entries);
The first example uses the Object.keys method to get an array of the object's keys.
The method returns an array of strings where the keys of the object are in the
same order as provided by a for...in
loop.
// 👇️️ ['one', 'two'] console.log(Object.keys({one: 1, two: 2}));
The second example shows how to use the Object.values method to get an array of the object's values.
Similarly to the keys method, the values are added to the array in the same
order as that provided by a for...in
loop.
// 👇️️ [1, 2] console.log(Object.values({one: 1, two: 2}));
The third example uses the Object.entries method, which returns a two dimensional array.
The nested arrays consist of 2 elements - the key and the value.
// 👉️ [ ['one', 1], ['two', 2] ] console.log(Object.entries({one: 1, two: 2}));
There are many applications for these nested arrays that contain key-value pairs. For example, they can be used to create an object, using the Object.fromEntries method.
const arr = [ ['one', 1], ['two', 2], ]; const obj = Object.fromEntries(arr); console.log(obj); // 👉️ {one: 1, two: 2}
The Object.fromEntries
method converts an array of key-value pairs into an
object.
Similarly you could also use an array of key-value pairs to create a Map
,
which is a data structure very similar to the object, where the insertion order
of keys is preserved and any value (objects and primitives) can be used as keys
or values.
const arr = [ ['one', 1], ['two', 2], ]; const map = new Map(arr); console.log(map); // 👉️ {'one' => 1, 'two' => 2}