How to convert an array into an object in JavaScript?

By IncludeHelp Last updated : January 27, 2024

Problem statement

Given an array, write JavaScript code to convert the given array into an object.

Converting an array into an object

The efficient way to convert an array into an object in JavaScript is to use the Object.assign() method by passing {} as its first parameter and the array as its second parameter.

Syntax to convert an array into an object

Below is the syntax to convert an array into an object in JavaScript:

Object.assign({}, array);

JavaScript code to convert an array into an object

In the below code, we have an array arr, and we are converting it into an object.

// Creating an array
const arr = [10, 20, 30, 40, 50];

// Printing array
console.log("arr: ", arr);

// Converting an array to an object
const obj = Object.assign({}, arr);

// Printing result (obj)
console.log("obj: ", obj);

Output

The output of the above code is:

arr:  [ 10, 20, 30, 40, 50 ]
obj:  { '0': 10, '1': 20, '2': 30, '3': 40, '4': 50 }
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.