Home >Backend Development >PHP Tutorial >How to convert object into array?

How to convert object into array?

王林
王林Original
2024-04-29 11:03:011333browse

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 object into array?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn