To convert an
object to an array, you can use the
`Object.keys()` or
`Object.entries()` method along with the `Array.map()` method. Here are examples of both approaches:
1. Using `Object.keys()`:
const obj = { name: 'John', age: 30, city: 'New York' };
const arr = Object.keys(obj).map(key => ({ key, value: obj[key] }));
console.log(arr);
In this example,
`Object.keys(obj)` retrieves an array of keys from the `obj` object. Then, `Array.map()` iterates over each key, and for each key, we create a new object with properties `key` and `value`, where `key` holds the current key from the iteration, and `value` holds the corresponding value from the original object.
2. Using `Object.entries()`:
const obj = { name: 'John', age: 30, city: 'New York' };
const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));
console.log(arr);
In this example,
`Object.entries(obj)` retrieves an array of key-value pairs from the `obj` object.
`Array.map()` iterates over each key-value pair, and for each pair, we destructure it into separate variables `key` and `value`. Then, we create a new object with `key` and `value` properties.
Both approaches will produce the same result, converting the object into an array of objects. The output will be:
[
{ key: 'name', value: 'John' },
{ key: 'age', value: 30 },
{ key: 'city', value: 'New York' }
]
Note:
Note that the order of the key-value pairs in the resulting array is not guaranteed to be the same as the original object, as objects in JavaScript do not have a specific order for properties.