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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY