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' }}
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:
const countryMap = countries.reduce((map, country) => {map[country.key] = countryreturn 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.
const mapToObject = function(map, obj) {map[obj.key] = objreturn map}const countryMap = countries.reduce(mapToObejct, {})
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.