Home >Backend Development >PHP Tutorial >What are the similar methods and differences between object to array and array to object?

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

PHPz
PHPzOriginal
2024-04-30 10:00:031038browse

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 the Object.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"]

Array to object

Similar method: Use Object.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" }

Difference:

  • Object.values() Returns an array containing the values ​​of an object's properties, while Object.fromEntries() returns a key-value pair object containing an array of properties.
  • Object.values() returns only enumerable properties, while Object.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!

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
Previous article:What is array slicing?Next article:What is array slicing?