In this quick article, we'll look at different ways to convert an array to an object in JavaScript. Let us start with the ES6's Object.assign().

Object.assign() Method

The Object.assign() method was introduced in ES6 and it copies the values of all enumerable own properties from one or more source objects to a target object. It has the following syntax:

Object.assign(target, ...sources)

The target object is the first argument and is also used as the return value. The following example demonstrates how you can use the Object.assign() method to convert an array to an object:

const names = ['Alex', 'Bob', 'Johny', 'Atta'];

// convert array to th object
const obj = Object.assign({}, names);

// print object
console.log(obj);

// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}

Spread Operator

Another way to convert an array to an object is by using the object spread ({... iterable}) operator. Here is an example:

const names = ['Alex', 'Bob', 'Johny', 'Atta'];

// convert array to th object
const obj = {...names};

// print object
console.log(obj);

// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}

for Loop

Both Object.assign() and object spread operator methods are the latest addition to JavaScript and only works in modern browsers.

For more browsers support, you should simply use the for loop to iterate over the array elements, and add them to an object:

const names = ['Alex', 'Bob', 'Johny', 'Atta'];

// create a new empty object
const obj = {};

// copy array elements to th object
for (let i = 0; i < names.length; i++) {
    obj[i] = names[i];
}

// print object
console.log(obj);

// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}

You can also add a function to Array's prototype and call it whenever you want to convert an array into an object:

// create a prototype method
Array.prototype.toObject = function() {
    const obj = {};

    // copy array elements to th object
    for (let i = 0; i < this.length; i++) {
        obj[i] = this[i];
    }

    return obj;
};

// convert array to object
const newObj = ['Alex', 'Bob', 'Johny', 'Atta'].toObject();

// print object
console.log(newObj);

// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.