Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

All the ways to turn an array into an object in JavaScript

In this article, I’m going to show you all the ways you can turn an array into an object in JavaScript with examples.

Let’s say we have an array of objects like so.

const users = [
    { 
        name: 'Amit',
        age: 30
    },
    { 
        name: 'Jemini',
        age: 30
    },
    { 
        name: 'Cherika',
        age: 6
    }
]

Now, if we want to convert this array into an object that is built using the name property as the key and the age property as the value, there are multiple ways to do so in JavaScript.

Using for…of loop

The first way is to use the for...of loop like so.

const userMap = {}

for (const user of users) {
    userMap[user.name] = user.value
}

console.log(userMap);
// { Amit: 30, Jemini: 30, Cherika: 6 }

Using Array.prototype.reduce

The second way is to use the Array.prototype.reduce method like so.

const userMap = users.reduce((acc, user) => {
    acc[user.name] = user.value
    return acc
}, {})

console.log(userMap);
// { Amit: 30, Jemini: 30, Cherika: 6 }

Using Object.fromEntries

The third way is to use the Object.fromEntries method like so.

const userMap = Object.fromEntries(
    users.map(user => [user.name, user.value])
)

console.log(userMap);
// { Amit: 30, Jemini: 30, Cherika: 6 }

Which one to use?

All of the above methods are valid and will give you the same result. But, if you ask me, I would prefer the Object.fromEntries method because it’s more concise and readable.

But if you’re concerned about the optimization, the for...of loop is the fastest among all of the above methods since it doesn’t create any intermediate arrays.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?