Home > Web Front-end > JS Tutorial > How Can I Convert a JavaScript Array into an Object?

How Can I Convert a JavaScript Array into an Object?

Patricia Arquette
Release: 2024-12-25 00:02:15
Original
804 people have browsed it

How Can I Convert a JavaScript Array into an Object?

Convert an Array to an Object

Converting an array into an object requires assigning values from the array to keys in the object. This task can be accomplished in several ways using JavaScript.

ECMAScript 6 Object.assign() Method

ECMAScript 6 introduces the Object.assign() method, which simplifies the process:

Object.assign({}, ['a', 'b', 'c']); // {0:"a", 1:"b", 2:"c"}
Copy after login

In this example, an empty object is created and values are copied from the array to the new object using Object.assign().

ES8 Spread Syntax

ES8 introduces spread syntax, which can also be used to convert an array to an object:

{...['a', 'b', 'c']}
Copy after login

This syntax creates an object with keys corresponding to the array elements and assigns the values accordingly.

reduce() Method

For more complex key-value assignments, the reduce() method can be used:

['a', 'b', 'c'].reduce((a, v) => ({...a, [v]: v}), {}) 
// { a: "a", b: "b", c: "c" }
Copy after login

In this case, the array is iterated over using reduce(), and a new object is created with custom keys and values.

The above is the detailed content of How Can I Convert a JavaScript Array into an 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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template