How to Filter Object Properties in JavaScript

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

How to Filter Object Properties in JavaScript
Picture by Blake Verdoorn

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. We can create a simple utility to do it.

/** * * @param obj The object we want to filter * @param predicate The callback function to filter properties * @returns Object */function filter(obj, predicate) {  const newObj = {};
  for (let prop in obj) {    if (obj.hasOwnProperty(prop) && predicate(obj[prop], prop, obj)) {      newObj[prop] = obj[prop];    }  }
  return newObj;}
/** * Usage */const greetings = {  a: 'Hello',  b: 'Hey',  c: 'Bye Bye'};const longGreetings = filter(greetings, value => value.length >= 5);// longGreetings ==> { a: 'Hello', c: 'Bye Bye' }

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

Last updated: