Max SchmittMS
16th July 2015

How to create an object from an array in JavaScript

I've been recently trying to incorporate a functional programming style wherever possible in my code. Here is a little snippet that you can use to create an object from an array for fast look-ups.


Let's say you have an array of objects that represent key-value-pairs like this:

const countries = [
{ key: 'de', value: 'germany' },
{ key: 'us', value: 'united states' },
{ key: 'uk', value: 'united kingdom' }

Now you're in a position where you want to find a given object by its key. If you only have an array, that is (I think) an O(n) lookup worst-case. An easy solution would be to create an object like this:

const countryMap = {
de: { key: 'de', value: 'germany' },
us: { key: 'us', value: 'united states' },
uk: { key: 'uk', value: 'united kingdom' }

Traditional approach: for-loop

Traditionally, you might just use a for-loop (or forEach):

const countryMap = {}
countries.forEach(country => (countryMap[country.key] = country))

I have to admit, forEach and the ES6 arrow-functions make this piece of code look not too bad. I still like the functional approach better:

Functional approach: reduce

const countryMap = countries.reduce((map, country) => {
map[country.key] = country
return map
}, {})

This functional approach should work better with immutable data and where it might be necessary to use the same function in a different place. A reduce function can easily be re-used.

Reusing a reduce function

const mapToObject = function(map, obj) {
map[obj.key] = obj
return map
const countryMap = countries.reduce(mapToObejct, {})
Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.