How to convert an object to an array in JavaScript: Use Object.keys() to get an array of property keys. Use Object.values() to get an array of property values. Convert object key-value pairs to arrays using map() and Object.entries().
How to convert an object into an array
In JavaScript, there are several ways to convert an object into an array:
Use Object.keys()
const obj = { a: 1, b: 2, c: 3 }; const keys = Object.keys(obj); // ['a', 'b', 'c']
Use Object.values()
const values = Object.values(obj); // [1, 2, 3]
Use combined operations
const arr = [...Object.values(obj)]; // [1, 2, 3]
Use map()
and Object.entries()
const entries = Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3]] const arr = entries.map(([key, value]) => value); // [1, 2, 3]
Practical case
Suppose we have an array of objects, and we want to get the array of id
attribute values of all objects:
const objects = [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' } ]; const ids = objects.map(({ id }) => id); // [1, 2, 3]
The above is the detailed content of How to convert object into array?. For more information, please follow other related articles on the PHP Chinese website!