Last updated: Mar 4, 2024
Reading timeยท3 min
Object.keys()
Object.entries()
Use the Object.values()
method to convert an object to an array of objects,
e.g. const arr = Object.values(obj)
.
The Object.values()
method takes an object as a parameter and returns an
array containing the object's property values.
const obj = { emp1: { id: 1, name: 'Alice', }, emp2: { id: 2, name: 'Bob', }, }; const arrayOfObjects = Object.values(obj); // ๐๏ธ [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ] console.log(arrayOfObjects);
The Object.values() method returns an array containing the object's values.
Here's an example of using the Object.values()
method without nested
properties.
// ๐๏ธ ['bobby', 'Chile'] console.log(Object.values({name: 'bobby', country: 'Chile'}));
Object.keys()
You can also use the Object.keys method to convert an object to an array of objects.
const obj = { emp1: { id: 1, name: 'Alice', }, emp2: { id: 2, name: 'Bob', }, }; const arrayOfObjects = Object.keys(obj).map(key => obj[key]); // ๐๏ธ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}] console.log(arrayOfObjects);
The Object.keys()
method returns an array of the object's keys.
const obj = { emp1: { id: 1, name: 'Alice', }, emp2: { id: 2, name: 'Bob', }, }; console.log(Object.keys(obj)); // ๐๏ธ [ 'emp1', 'emp2' ]
The function we passed to the Array.map() method gets called with each element in the array.
On each iteration, we return the value of each key.
The map()
method returns a new array containing the values returned from the
callback function.
Object.entries()
The Object.entries() method can be used to transform the object into an array of key-value pairs.
const obj = { emp1: { id: 1, name: 'Alice', }, emp2: { id: 2, name: 'Bob', }, }; // [ // [ 'emp1', { id: 1, name: 'Alice' } ], // [ 'emp2', { id: 2, name: 'Bob' } ] // ] console.log(Object.entries(obj));
You can use the Array.map()
method to return only the value of each key.
const obj = { emp1: { id: 1, name: 'Alice', }, emp2: { id: 2, name: 'Bob', }, }; const arrayOfObjects = Object.entries(obj).map(entry => entry[1]); // ๐๏ธ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}] console.log(arrayOfObjects);
You can also use the Object.entries()
method to preserve the nested keys of
the object when converting it to an array of objects.
const obj = { emp1: { id: 1, name: 'Alice', }, emp2: { id: 2, name: 'Bob', }, }; const withNestedKeys = Object.entries(obj).map(entry => { return {[entry[0]]: entry[1]}; }); // [ // { emp1: { id: 1, name: 'Alice' } }, // { emp2: { id: 2, name: 'Bob' } } // ] console.log(withNestedKeys);
We used the Array.map()
method to iterate over the array.
On each iteration, we return an object and preserve the key-value pair structure of the original object.
When you use this approach all of the key-value pairs of the object get transferred to the objects in the array.
You can learn more about the related topics by checking out the following tutorials: