Es6 map an array of objects, to return an array of objects with new keys
Use ES6's map
function to redefine keys in your objects:
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:
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:
With ES6 map
, keys become more descriptive:
Revel in the success of your transformation:
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
ornull
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 likefilter
for enhanced transformations.
Was this article helpful?