Explain Codes LogoExplain Codes Logo

Javascript reduce() on Object

javascript
reduce
object-transformation
javascript-good-practices
Nikita BarsukovbyNikita Barsukov·Feb 27, 2025
TLDR
const result = Object.entries(obj).reduce((acc, [key, value]) => { acc[key] = value * 2; // Example: We're multiplying by 2, but feel free to replace with your operation. return acc; }, {});

Use Object.entries(obj) to change object obj into an array of [key, value] pairs, then use reduce() to transform these pairs as needed, here doubling each value. Accumulate the result into a new object acc.

Reducing object properties: Quick Hits

Reducing an object in JavaScript is carried out by using array functions on object's iterable versions. Object.keys(), Object.values(), and Object.entries() are your partners in this.

Summing object values

const sum = Object.values(obj).reduce((total, value) => total + value, 0);

The above code snippet adds up values in object property using Object.values() in an efficient and neat way.

Merging objects

const merged = Object.keys(obj).reduce((acc, key) => { Object.assign(acc, obj[key]); return acc; }, {});

Merging nested objects, sound complex? Look above; it's simpler than you thought.

Complex Aggregations

const stats = Object.entries(obj).reduce((acc, [key, value]) => { acc[key] = value + (acc[key] || 0); // The || 0 is not a meditation mantra, it handles undefined cases. return acc; }, {});

When both keys and values are involved in reduction, Object.entries() reaches the rescue.

JavaScript Good Practices and Tricky Parts

When using reduce on objects, some practices keep you out of troublesome gotchas!

Object Properties: An orderly chaos

Remember that order of object properties can be as unpredictable as a drunken sailor's walk. The outcomes of reducing an object might swing in different directions across environments, where order matters.

Initial value: A good start

Always specify an initial value for the reduce function to actively dodge errors on empty objects or non-conforming result types.

Destructuring in reduce callbacks

Destructuring in reduce callbacks can lead you directly to values, saving you from names longer than a royal title.

Reduce vs. Map

Reduce() accumulates values. Map() transforms them. Don't mix them up, or your array will give you the stink-eye.

ES6: The cool kid's syntax

Use ES6, the stylish and concise syntax, to write better understandable code.

More than Just Reduction: Object Transformations

Reduce is not a one-trick pony. Paired with Object.keys() or Object.entries(), it can transform an object into new data structures:

Object to Map

const objMap = new Map(Object.entries(obj));

The above code turns an object into a Map or as I like to call it, a trendy object.

Array of Objects

const objectsArray = Object.keys(obj).map(key => ({ [key]: obj[key] }));

Ever wondered how an object would look as an array of objects? You're welcome.

Get Out of the Edge Cases

The usage of reduce on objects can introduce edge cases, which like unwelcome guests, are better handled before they cause trouble.

Deep Cloning with Nested Objects

When nested properties and "no touch" policy for the original object come together, deep cloning is the solution:

const deepMerge = Object.keys(obj).reduce((acc, key) => { acc[key] = { ...obj[key] }; // A clone more perfect than a stormtrooper. return acc; }, {});

Empty Objects: Handling nothingness

Before using reduce, "empty" is not just philosophical concept, it's a use-case to handle:

const isEmpty = obj && Object.keys(obj).length === 0; const result = isEmpty ? { message: 'No data' } : /* REDUCE LOGIC */;

Conditional reduction

Sometimes, you want to be picky about what to accumulate. Can relate, right?

const selectiveSum = Object.values(obj).reduce((sum, value) => { return value > 10 ? sum + value : sum; // The Snobby Accumulator: Only sums values greater than 10. }, 0);