How to convert an object to an array
Short answer
Object.values() returns the values, Object.keys() returns the keys:
const prices = { tea: 3, coffee: 4, cake: 5 };
console.log(Object.keys(prices).join(', '));
console.log(Object.values(prices).join(', '));Output:
tea, coffee, cake
3, 4, 5Pairs
Object.entries() returns pairs of a key and a value:
const prices = { tea: 3, coffee: 4 };
console.log(JSON.stringify(Object.entries(prices)));Output:
[["tea",3],["coffee",4]]An array of objects
Often you need a list of objects, for example to show a table:
const prices = { tea: 3, coffee: 4 };
const rows = Object.entries(prices).map(([name, price]) => ({ name, price }));
console.log(JSON.stringify(rows));Output:
[{"name":"tea","price":3},{"name":"coffee","price":4}]Common mistake
Array.from() does not work with an ordinary object, it gives an empty array:
console.log(Array.from({ tea: 3, coffee: 4 }).length);Output:
0Functions used in this recipe
- Object.keys — Returns an array of an object's property names.
- Object.values — Returns an array of an object's property values.
- Object.entries — Returns an array of property name and value pairs.