How to Filter an Object with JavaScript

Dec 21, 2020

JavaScript's array filter() function is a handy function that takes a function callback and returns a new array with just the elements for which callback returned true.

const numbers = [1, 2, 3, 4, 5, 6];

let callback = v => v % 2 === 0;
const even = numbers.filter(callback);
even; // [2, 4, 6]

callback = v => v % 2 === 1;
const odd = numbers.filter(callback);
odd; // [1, 3, 5]

Unfortunately, JavaScript objects don't have a filter() function. But that doesn't mean you can't use filter() to filter objects, you just need to be able to iterate over an object and convert the object into an array using Object.entries().

const numWins = {
  'BUF': 11,
  'MIA': 9,
  'NE': 6,
  'NYJ': 1
};

// Convert `numWins` to a key/value array
// `[['BUF', 11], ['MIA', 9], ...]`
const asArray = Object.entries(numWins);

// Use `filter()` to filter the key/value array
const atLeast9Wins = asArray.filter(([key, value]) => value >= 9);

// Convert the key/value array back to an object:
// `{ 'BUF': 11, 'MIA': 9 }`
const atLeast9WinsObject = Object.fromEntries(atLeast9Wins);

You can implement this logic as a one-liner, but it is a bit messy:

function filterObject(obj, callback) {
  return Object.fromEntries(Object.entries(obj).
    filter(([key, val]) => callback(val, key)));
}

You can implement this more elegantly using Lodash's flow() function, which behaves like a pipe() function that lets you chain static methods like Object.fromEntries() and Object.entries().

const numWins = {
  'BUF': 11,
  'MIA': 9,
  'NE': 6,
  'NYJ': 1
};

const atLeast9Wins = _.flow([
  Object.entries,
  arr => arr.filter(([key, value]) => value >= 9),
  Object.fromEntries
])(numWins);

atLeast9Wins; // { BUF: 11, MIA: 9 }

More Fundamentals Tutorials