JavaScript – Convert an array to an object

There are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches –

Using reduce()

const array = [['name', 'Josh'], ['age', 25], ['city', 'New York']];

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

console.log(obj); // Output: { name: 'Josh', age: 25, city: 'New York' }

In the above example, we have used the reduce method that iterates over each pair, destructuring them into key and value. It then assigns each value to its corresponding key in the accumulator object.

Using Object.fromEntries()

const array = [['name', 'Josh'], ['age', 25], ['city', 'New York']];

const obj = Object.fromEntries(array);

console.log(obj); // Output: { name: 'Alice', age: 25, city: 'New York' }

The Object.fromEntries() method in JavaScript is a standard built-in method used to transform a list of key-value pairs into an object.

Similar Reads