Javascript reduce() on Object
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
The above code snippet adds up values in object property using Object.values()
in an efficient and neat way.
Merging objects
Merging nested objects, sound complex? Look above; it's simpler than you thought.
Complex Aggregations
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
The above code turns an object into a Map or as I like to call it, a trendy object.
Array of Objects
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:
Empty Objects: Handling nothingness
Before using reduce, "empty" is not just philosophical concept, it's a use-case to handle:
Conditional reduction
Sometimes, you want to be picky about what to accumulate. Can relate, right?
Was this article helpful?