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 obj = {
  name: 'Luke Skywalker',
  title: 'Jedi Knight',
  age: 23
};

// Convert `obj` to a key/value array
// `[['name', 'Luke Skywalker'], ['title', 'Jedi Knight'], ...]`
const asArray = Object.entries(obj);

const filtered = asArray.filter(([key, value]) => typeof value === 'string');

// Convert the key/value array back to an object:
// `{ name: 'Luke Skywalker', title: 'Jedi Knight' }`
const justStrings = Object.fromEntries(filtered);

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 }

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!