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 introduces the Object.assign() method, which simplifies the process:
Object.assign({}, ['a', 'b', 'c']); // {0:"a", 1:"b", 2:"c"}
In this example, an empty object is created and values are copied from the array to the new object using Object.assign().
ES8 introduces spread syntax, which can also be used to convert an array to an object:
{...['a', 'b', 'c']}
This syntax creates an object with keys corresponding to the array elements and assigns the values accordingly.
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" }
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!