View profile

Functional Programming with JavaScript Objects

Functional Programming with JavaScript Objects
By Mastering JS Weekly • Issue #52 • View online
I’ve seen more than a few junior developers get confused because arrays are objects in JavaScript, but you can’t use methods like `filter()` and `map()` with objects. Iterating over a JavaScript object has more nuance than iterating over an array.
One of the more underrated features of the 2017 edition of the JavaScript language spec was `Object.entries()`. Async/await got all of the hype, but the idea of “entries” made it possible to think of objects as arrays.

What is an Entry?
The JavaScript language spec defines an internal abstract operation “AddEntriesFromIterable” that defines an entry as an array with 2 elements. The first element is assumed to be the key, and the second element is assumed to be the value.
An object as a POJO or as an array of entries
An object as a POJO or as an array of entries
This “array of arrays” syntax lets you think of a POJO as an array, which means you can then use functional programming primitives like `filter()` and `map()` to modify the object. For example, filtering an object is easy using the entries form.
Filter an object, taking only values that are numbers
Filter an object, taking only values that are numbers
The trick is converting back and forth between entries and POJOs. The `Object.entries()` function converts an object into an array of entries, and `Object.fromEntries()` converts an array of entries back into a POJO.
Switching between array of entries and POJOs
Switching between array of entries and POJOs
Most Recent Tutorials
How to Use forEach() in JavaScript - Mastering JS
How to Filter an Object with JavaScript - Mastering JS
JavaScript Trim String - Mastering JS
Other Interesting Reads
JavaScript Object.fromEntries() | SamanthaMing.com
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue