Convert object to array in Javascript / React
Solution 1:
You can use Object#values
(ECMAScript 2017), but it's not supported by IE (see browser's compatibility).
Note: The ECMAScript 6 specification defines in which order the properties of an object should be traversed. This blog post explains the details.
const map = { a: 1, b: 2, c: 3 };
const result = Object.values(map);
console.log(result);
If you need to support IE, you can use Object#keys
with Array#map
:
const map = { a: 1, b: 2, c: 3 };
const result = Object.keys(map).map((key) => map[key]);
console.log(result);
Solution 2:
I am not sure by map you mean the Map object or an ordinary JS object. However, just for variety I would like to mention that the Map objects are mostly (probably always) stringified like JSON.stringify([...myMap])
. So if you happen to receive a Map object in JSON data may be you should do something like;
var myMap = new Map().set(1,"hey").set(2,"you"),
mapData = JSON.stringify([...myMap]),
values = JSON.parse(mapData).map(d => d[1]);
console.log("mapData:",mapData);
console.log("values:",values);