In JavaScript, an array represents a collection of items, whereas an object represents a collection of key-value pairs. There are situations where converting an array into an object can enhance the ease of accessing specific items within it. There are several ways to convert arrays into objects, depending on your specific requirements and the structure you want for the resulting object In this article, we'll explore various methods for converting an array to an object in javascript.

convert an array to an object


Table of Contents

1. Using a For Loop:

Iterate the array of elements and manually create key-value pairs to construct an object. This approach gives you full control over the object's structure.

Example:-

const convertArrayToObject = (arr) => {
let obj = {};
for (let i = 0; i < arr.length; i++) {
obj[i] = arr[i];
}
return obj;
};

const arr = ['A', 'B', 'C', 'D'];
const obj = convertArrayToObject(arr);
console.log(obj); // {0: 'A', 1: 'B', 2: 'C', 3:'D'}


2. Using the reduce Method:

The reduce method allows you to accumulate values from an array into a single object. You can define a callback function that transforms each array element into a key-value pair.

Example1:-

const array = ['a', 'b', 'c','d'];

const obj = array.reduce((acc, currentValue, index) => {
acc[index] = currentValue;
return acc;
}, {});

console.log(obj); // {0: 'a', 1: 'b', 2: 'c',3: 'd'}


Example2:-

If an array contains 2-element arrays where first element is the key and second element is the value. So you can easily convert the array to object using reduce.

const array = [
["key1","value1"],
["key2", "value2"],
["key3", "value3"]
]
const obj = array.reduce((acc, [key, value])=>({...acc, [key]: value}), {});

console.log(obj)

Output:

{
key1: 'value1',
key2: 'value2',
key3: 'value3'
}


3. Using the Object.fromEntries() method

You can use the Object.fromEntries() method to create an object from an array of key-value pairs

Example:

const props = [
['name', 'Nagi'],
['color', 'White'],
['age', 19],
];

const obj = Object.fromEntries(props);
console.log(obj);

Output

{ name: 'Nagi', color: 'White', age: 19 }


4. Using the Object.assign() method

You can use the Object.assign() method to create a new object by merging the properties of an array into an empty object.

Example:

const arr = ['A', 'B', 'C', 'D', 'E'];
const obj = Object.assign({}, arr);
console.log(obj);

Output

{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}

Note: Choose the method that fulfil your needs based on the input data and the required output format. The Object.fromEntries method is especially handy when you have an array of key-value pairs and want to convert it into an object.

Here is the stack-overflow link to see more answers on this