Borislav Hadzhiev
Sun Oct 10 2021·2 min read
Photo by Aubrey Odom
To get the values of an object as an array, use the Object.values()
method,
passing it the object as a parameter. 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);
In the code snippet we use the Object.values method to get the object's values.
Object.values
method is not supported in Internet Explorer. If you have to support the browser, use the next approach this article covers.// Supported in IE 9-11 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 use the Object.keys method to get an array containing the object's keys.
We then iterate over the keys using Array.map and return the value for each key.
The function we pass to the map
method gets invoked for each key in the keys
array.
map
method returns a new array containing the values we returned from the callback function passed to the method.This approach is a bit more indirect and verbose, however if you have to support Internet Explorer, it gets the job done.