Better Programming

Advice for programmers.

Follow publication

Member-only story

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

Marco Antonio Ghiani
Better Programming
Published in
5 min readAug 29, 2019

--

Photo by Blake Richard Verdoorn on Unsplash

Exciting news! I’m moving all of my content into one home — my personal website https://marcoghiani.com/.

Everything will be easier to find, better organized, and packed with fresh updates.

To stay in the loop and never miss a beat, be sure to subscribe to my newsletter! You’ll be the first to know about new posts, exclusive content, and more!

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.

--

--

Marco Antonio Ghiani
Marco Antonio Ghiani

Written by Marco Antonio Ghiani

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

Responses (8)

Write a response