JavaScript Tips #1: The Filter Method for Object Properties.

A simple JavaScript polyfill of the filter array method applied to object properties

Marco Antonio Ghiani
Aug 29 · 2 min read
Photo by Blake Richard Verdoorn on Unsplash

The Problem

How often do you find yourself managing a massive object received from a third-party API or reading data from a JSON file? In JavaScript, objects are everywhere, and many times we need to add, remove, or edit properties of them. And we’d also like to generate a new object so we don’t change the original one.

ECMAScript 5.1 provided us with a wonderful Array.prototype.filter method to filter arrays and return only lists of values filtered by our condition. But for the same operation on objects, we always have to go for less functional approaches.

The Solution

One option is to filter our object properties. If it’s a recurrent operation, we could polyfill a method for the Object prototype, which does it for us:

Now you can easily filter the object properties passing a predicate callback, which return “true” or “false,” to filter the object properties.

This implementation iterates only over the own and enumerable properties of the object.

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Marco Antonio Ghiani

Written by

“If it takes less than two minutes, then do it now.” D.A. Coding JS at @xceed. In love with coding.

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade