Explain Codes LogoExplain Codes Logo

Es6 map an array of objects, to return an array of objects with new keys

javascript
map-function
object-destructuring
array-transformation
Nikita BarsukovbyNikita Barsukov·Feb 6, 2025
TLDR

Use ES6's map function to redefine keys in your objects:

const transformedArray = originalArray.map(({ oldKey1: value, oldKey2: text }) => ({ value, text }));

Here we destructure the properties (oldKey1, oldKey2) from the original object and rename them to value and text for use in React UI components.

Fixing your lock & key troubles

If you're looking to change the keys of the objects in your array, this is the right avenue. Let's delve into how you can make it happen.

The magic of ES6 to your rescue

To perform this transformation, we consciously wield the power of arrow functions and object destructuring. Our object literal is nestled safely within parentheses to make sure JavaScript recognizes what we're trying to do and doesn't interpret it as a block statement.

React in action

The power of these transformations can be seen directly when working with React or a similar library. Need to feed data to a dropdown? Simplify your life with your newly transformed keys:

<select> {transformedArray.map(option => ( <option value={option.value}>{option.text}</option> ))} </select>

Note: This select won't select anything fashionable for you.

Image is everything

Gravity towards brevity exists but remember clarity is a virtue. Concision comes with practice and familiarity, so while a transformation can be written as a concise one-liner, don't compromise readability for compactness.

How does your array look now?

Gone are the days of mundane keys:

Before: [{a,b,c}, {a,b,c}, {a,b,c}]

With ES6 map, keys become more descriptive:

array.map(obj => ({ value: obj.a, text: obj.b }));

Revel in the success of your transformation:

After: [{value,text}, {value,text}, {value,text}]

A round of applause for the hero of the hour, ES6! 👏

Dealing with the unexpected

This section discusses variations, enhancements, and words of caution for key remapping.

Preparing for curveballs

  • Null checks: Check for undefined or null before you destructure.
  • Dynamic keys: If you must set keys based on dynamic values, use [computedPropertyName].
  • Performance: Map is efficient with large datasets, but do consider other methods for performance-critical tasks.

Taking one step further

  • Deep cloning: Achieve deep cloning of objects with map and the spread operator ....
  • Conditional mapping: Patio furniture not included, but you can definitely integrate conditions into your map function.
  • Chained methods: Merge map with other array methods like filter for enhanced transformations.