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

How to convert object into array?

王林
Release: 2024-04-29 11:03:01
Original
1356 people have browsed it

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']
Copy after login

Use Object.values()

const values = Object.values(obj); // [1, 2, 3]
Copy after login

Use combined operations

const arr = [...Object.values(obj)]; // [1, 2, 3]
Copy after login

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]
Copy after login

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]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template