Categories
JavaScript Answers

How to Map Over a JavaScript Object While Preserving the Keys?

Spread the love

We can use the Lodash mapValues method to map property values of a JavaScript object to new values.

For instance, we can write:

const mapped = _.mapValues({
  one: 1,
  two: 2,
  three: 3
}, (v) => {
  return v * 3;
});
console.log(mapped)

We pass in the object we want to transform the property values for as the first argument.

Then we pass in a function to return the mapped value given the property value v ,

Therefore, mapped is:

{one: 3, two: 6, three: 9}

Use the Object.entries and Object.assign Methods

We can use the Object.entries method to get the key-value pairs of an object as an array.

Then we can call map to maps the key-value pair to what we want.

And then we can use Object.assign to create a new object from the key-value pairs.

For instance, we can write:

const obj = {
  one: 1,
  two: 2,
  three: 3
}
const props = Object.entries(obj).map(([k, v]) => ({
  [k]: v * 3
}))
const mapped = Object.assign(...props);
console.log(mapped)

We call Object.entries with obj .

Then we call map to map the v property value to their new values and return an array of objects each with their own key-value pair with the mapped property value.

Next, we spread the props into Object.assign with the props array spread into Object.assign as arguments.

Therefore, mapped is the same as the previous example.

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 *