Introducing build-object-better for JavaScript
Introducing my new build-object-better
package , now available on npm.
One of my favorite patterns in JavaScript is creating an object from its properties using Array.reduce
, as in the following (somewhat contrived) examples:
One of my least favorite patterns in JavaScript is creating an object from its properties using Array.reduce
, as in the preceding examples.
The pattern is really useful and powerful, but it’s so ugly. If it’s a new pattern to you, it’t not particularly intuitive what it’s doing. The reduce
method on Array
is already slightly esoteric for new comers to functional programming, and the idea of using it to mutate a single object over and over (instead of returning a new value for each iteration as with a straight forward summation example), only adds to the confusion.
Besides which, it’s just a lot to write. You have to remember the initial empty object as the second argument to reduce
(which by that time is so far away that you’ve probably forgotten you were even calling reduce
); you have to remember to accept the accumulated value (obj
in the examples above) in your reducing function, and then also return it, which you have to do as a separate statement (or use the oft-maligned comma-operator).
It’s a small but annoying amount of boiler plate that really distracts you and the reader from what you really care about, which is how the values you’re iterating over are used to determine the property values of the object you’re creating. It also all but forces even a trivial object creation from being written on a single line, and therefore breaks the flow of the surrounding code.
I got tired of writing this pattern, and tired of creating obj-util.js
modules to encapsulate this in forty-percent of the projects I work. So I compiled together the best examples of obj-utils.js
I could find on my laptop, and put together the build-object-better
package on npm.
It’s a pretty trivial package that offers a few convenient variations on the pattern so you can skip most of the boiler plate, and focus on what really matters. The examples below are the same as those above, but implemented using the build-object-better
package:
I hope you find it helpful; weighing in at just 136 lines of code (including comments and whitespace) and 3085 bytes (607 bytes for just the minified source, or 351 bytes compressed), with no dependencies, it’s a pretty lightweight addition to your project.
If you have any feedback, please comment below or create an issue on the github project.
May your boilerplate be minimal, and your code read like a story. Happy object building!