Home > Web Front-end > JS Tutorial > How to Convert an Array to an Object in JavaScript?

How to Convert an Array to an Object in JavaScript?

Linda Hamilton
Release: 2024-12-13 17:02:10
Original
107 people have browsed it

How to Convert an Array to an Object in JavaScript?

How to Transform an Array into an Object

Converting an array into an object may seem like a straightforward operation, but there are several methods to achieve this depending on the desired outcome.

Consider the following task: converting the array ['a','b','c'] into an object with numeric keys:

{
  0: 'a',
  1: 'b',
  2: 'c'
}
Copy after login

ES6 Object.assign()

Modern browsers support Object.assign(), which conveniently copies the enumerable properties of one or more source objects to a target object:

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

Note that the array's length property is not copied as it's not enumerable by default.

ES8 Spread Syntax

ES8's spread operator can also be used to spread the array elements into an object:

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

Custom Key Assignment

For more complex scenarios, using reduce with a custom key transformation function can achieve the desired result:

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

Each approach offers its own advantages and trade-offs. Object.assign() and spread syntax are straightforward and concise, while reduce provides more flexibility when dealing with custom keys or transformations.

The above is the detailed content of How to Convert an Array to an Object in JavaScript?. 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