creates an array from an object in javascript

To create an array from an object in JavaScript, you can use the Object.keys() method to get an array of keys from the object, and then use the Array.map() method to create a new array from the keys. Here is some sample code:

index.tsx
const obj = {one: 1, two: 2, three: 3};
const arr = Object.keys(obj).map(key => obj[key]);
console.log(arr); // Output: [1, 2, 3]
130 chars
4 lines

In this code, we first define an object obj with three key-value pairs. We then use the Object.keys() method to get an array of keys (['one', 'two', 'three']), and use the Array.map() method to iterate over the keys and map them to an array of values ([1, 2, 3]). Finally, we log the resulting array to the console.

related categories

gistlibby LogSnag