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, {})

Need help on a project?

I'm available for freelance work.
Send me an email! Or find out more about my services.