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' }
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"}
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'] }
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" }
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!