How to Filter an Object by Key and Value in JavaScript

Aug 13, 2021

To filter an object by key-value, you can iterate over the object 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);

Using for/of and Object.entries()

Object.entries() returns a 2 dimensional array of the key-value pairs. Each element in the array has 2 elements: the first is the key, and the 2nd is the value. So you can iterate over the array using for/of and create a new object with just the properties you want.

const obj = {
  name: 'Luke Skywalker',
  title: 'Jedi Knight',
  age: 23
};

const newObj = {};
for (const [key, value] of Object.entries(obj)) {
  if (typeof value === 'string') {
    newObj[key] = value;
  }
}

// `{ name: 'Luke Skywalker', title: 'Jedi Knight' }`
newObj;

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!