Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
Use the Object.values()
method to get an object's values as an array, e.g.
const values = Object.values(obj);
.
The method returns an array containing the object's property values in the
same order as provided by a for ... in
loop.
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; const values = Object.values(obj); // ๐๏ธ [1, 'Chile', 'Santiago'] console.log(values);
We used the Object.values() method to get the object's values as an array.
Alternatively, you can use the Object.keys()
method.
To get an object's values as an array:
Object.keys()
method to get an array of the object's keys.Array.map()
method to iterate over the array.const obj = {id: 1, country: 'Chile', city: 'Santiago'}; // ๐๏ธ ['id', 'country', 'city'] const keys = Object.keys(obj); console.log(keys); const values = keys.map(key => { return obj[key]; }); // ๐๏ธ [1, 'Chile', 'Santiago'] console.log(values);
We used the Object.keys() method to get an array containing the object's keys.
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; // ๐๏ธ ['id', 'country', 'city'] const keys = Object.keys(obj); console.log(keys);
The next step is to iterate over the array of keys using Array.map() and return the value of each key.
The function we passed to the Array.map()
method gets invoked for each key in
the keys array.
Array.map()
method returns a new array containing the values we returned from the callback function.This approach is a bit more indirect and verbose and should only be used if you have to support very old browsers like Internet Explorer.
An alternative approach used to get an object's values as an array is to use a
for...in
loop.
for...in
loop #To get an object's values as an array:
for...in
loop to iterate over the object.const obj = {id: 1, country: 'Chile', city: 'Santiago'}; const valuesArray = []; for (const key in obj) { valuesArray.push(obj[key]); } // ๐๏ธ [ 1, 'Chile', 'Santiago' ] console.log(valuesArray);
We used the for...in
loop to iterate over the object.
On each iteration, we use the current key to get the value and push the value into a new array.
Which approach you pick is a matter of personal preference. I'd use the
Object.values()
method as it is quite direct and intuitive.