Occasionally, you might need to perform a certain operation on each value within an object. Whether you need to modify numerical values, format strings, or perform any other type of transformation, JavaScript offers various approaches to achieve this task.
In this guide, I will show you, how you can achieve that task on all elements of an object in JavaScript, providing a concise and effective way to manipulate object data.
Snippet
We will use a functional approach with Object.entries()
and Array.prototype.reduce()
// Sample object
const numbers = {
a: 1,
b: 2,
c: 3
};
// Function to multiply by 2 all the elements of the object
function transformObject(object) {
return Object.entries(object).reduce((newObject, [key, value]) => {
newObject[key] = value * 2;
return newObject;
}, {});
}
console.log(transformObject(numbers));
// Output: { a: 2, b: 4, c: 6 }
Explanation
- We use
Object.entries(obj)
to obtain an array of[key, value]
pairs from the object. - With
Array.prototype.reduce()
, we apply the transformationvalue * 2
to each value, building a new objectnewObject
with the transformed values.
Transforming object values in JavaScript is a common task, and there are multiple approaches to accomplish it. The choice of method depends on factors such as readability, performance, and personal preference. the decision on which to use depends on the specific requirements and coding style preferences of your project.
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts or opinions below in the comments section. You can have more of my content by following me on LinkedIn • GitHub or Medium