What are the similar methods and differences between object to array and array to object?

PHPz
Release: 2024-04-30 10:00:03
Original
960 people have browsed it

Object to array method: use the Object.values() method to return an array of attribute values; array to object method: use the Object.fromEntries() method to return a key-value pair object containing an array pair. The difference is: Object.values() only returns enumerable property values, while Object.fromEntries() returns all properties whether enumerable or not.

What are the similar methods and differences between object to array and array to object?

Similar methods and differences between object to array and array to object

Object to array

Similar methods:Use theObject.values()method, which returns an array containing all enumerable property values of the object.

Code example:

const obj = { name: "John", age: 30, city: "New York" }; const arr = Object.values(obj); console.log(arr); // ["John", 30, "New York"]
Copy after login

Array to object

Similar method:UseObject.fromEntries()method, which receives an array array pair parameter and returns an object containing these key-value pairs.

Code example:

const arr = ["name", "John", "age", 30, "city", "New York"]; const obj = Object.fromEntries(arr); console.log(obj); // { name: "John", age: 30, city: "New York" }
Copy after login

Difference:

  • Object.values()Returns an array containing the values of an object's properties, whileObject.fromEntries()returns a key-value pair object containing an array of properties.
  • Object.values()returns only enumerable properties, whileObject.fromEntries()returns all properties whether enumerable or not.

The above is the detailed content of What are the similar methods and differences between object to array and array to object?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!