Converting Array into an Object in JavaScript
In this tutorial, we are going to learn about three different ways to convert an array into an object in JavaScript.
Es6 spread operator (…)
We can use the es6 spread operator us to convert an array into an object.
Example:
let array = ["cabin","cake","cable"];
let object = {...array};
console.log(object); // {0: "cabin", 1: "cake", 2: "cable"}
Array.reduce() method
The reduce()
method is also used to convert an array to an object, but we need to pass empty object {}
as a second argument to it.
Example:
let array = ["cabin","cake","cable"];
let object = array.reduce((acc,current,i)=>{
acc[i] = current;
return acc;
}, {});
console.log(object); // {0: "cabin", 1: "cake", 2: "cable"}
Let’s learn how the above code works.
The first time the callback is called, the accumulator value is equal to an object. so that we stored the each array value into an object by using acc[i] = current
, at final we returned accumulator (which is an object).
Object.assign() method
The Object.assign()
method is used to copy all enumerable own properties from one or more source objects to a target object.
In our case, we need to pass target
as an empty object and source
is the array we need to convert as an object.
Example:
let array = ["cabin","cake","cable"];
// target, source
let object = Object.assign({}, array);
console.log(object); // {0: "cabin", 1: "cake", 2: "cable"}