Icons by Font Awesome

Mapping objects in JavaScript

Johann Pardanaud
Mar 16, 2018 · 1 min read

JavaScript has been evolving fast these last years, but object mapping is still a tricky part for beginners, especially if you don't want to mutate the original object.

Here are some code examples for ES5, ES2015 and ES2017+. They all use the map and reduce methods available on arrays. These two methods allow to separate the mapping logic from the object construction.

For each example, the goal is to transform this object:

{
a: 1,
b: 2,
}

To this one:

{
_a: 2,
_b: 3,
}

ES5

ES2015 (ES6)

ES2017+

In the future

A new stage-0 proposal has been presented to add Object.fromEntries, this could provide us a new way to write the last example:

And it would be even better with the pipeline operator (stage-1) to keep the method chaining:

Johann Pardanaud

Written by

Web developer working at batch.com - Passionate climber

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade