Categories
JavaScript Answers

How to map over object preserving keys with JavaScript?

Spread the love

Sometimes, we want to map over object preserving keys with JavaScript.

In this article, we’ll look at how to map over object preserving keys with JavaScript.

How to map over object preserving keys with JavaScript?

To map over object preserving keys with JavaScript, we can use the Object.fromEntries and Object.entries methods.

For instance, we write

const newObj = Object.fromEntries(
  Object.entries(obj).map(([k, v]) => [k, v * 3])
);

to call Object.entries with obj to return an array of key-value pair arrays.

Then we call map to map each entry to an array with key k and new value v * 3, where v is the original property value.

Next, we call Object.fromEntries to convert the nested array back to an object.

Conclusion

To map over object preserving keys with JavaScript, we can use the Object.fromEntries and Object.entries methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *