How to Map Values of a Javascript Object to a New Object Using a Function?
To map values of a JavaScript object to a new object using a function, you can use the Object.keys()
method to get all the keys of the object, and then use the Array.prototype.reduce()
method to create a new object with the result of applying the function to each key-value pair. Here's an example:
const originalObject = { a: 1, b: 2, c: 3 };
const mappedObject = Object.keys(originalObject).reduce((result, key) => {
result[key] = myFunction(originalObject[key]);
return result;
}, {});
function myFunction(value) {
// Replace this with your own function to transform the value
return value * 2;
}
console.log(mappedObject); // { a: 2, b: 4, c: 6 }
In this example, Object.keys(originalObject)
returns an array of all the keys in the original object (["a", "b", "c"]
). The reduce()
method processes each key-value pair and accumulates the results in a new object ({}
).
Inside the reduce function, myFunction
is called with the value of each key, and the result of the function is assigned to the corresponding key in the result
object.
Finally, the mappedObject
variable contains the new object with the transformed values. You can replace myFunction
with your own function to transform the values in any way you like.