by Sai gowtham

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"}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course