Object filtering

Filtering objects as easily as arrays.


function objectFilter(obj, func = ([, val]) => val) {
  return Object.fromEntries(Object.entries(obj).filter(func));
}
js

Context

In JavaScript, since almost everything is an object we are constantly manipulating them and filtering is obviously one of the most common use cases. Let's say we want to get an object with just the keys and values that fullfil a certain condition. For arrays we would just use filter() unfortunately for objects filter() doesn't support objects.

But, what we can do is convert our object to an array first so that we are able to iterate over the object as if it was an array, before filtering it as intended. Let's see how we can do it using our objectFilter() function:

Usage

// Filtering null values by default
objectFilter({
  firstName: null ,
  lastName: "Doe",
  age: 26,
}); // { lastName: "Doe", age: 26 }

// Using our own filtering
objectFilter(
  {
    firstName: "John",
    lastName: "Doe",
    age: 26,
  },
  ([, val]) => typeof val === "number"
);
// { age: 26 }
js

Explanation

This function takes two parameters, an object to be filtered and an optional callback function which will be provided to filter() that basically returns every value that meets the condition so the provided callback better return a boolean.

const obj = {
  firstName: "John",
  LastName: "Doe",
  age: 26,
};

// Convert *obj* to a [key, value] array of arrays
const objAsArray = Object.entries(obj);
// `[['firstName', 'John'], ['lastName', 'Doe'], ['age', 26]]`

const filteredObj = objAsArray.filter(
  ([key, value]) => typeof value === "number"
);
// `[['age', 26]]`

// Convert the key/value arrays back to an object:
const objNumbersOnly = Object.fromEntries(filteredObj);
// `{ age: 26 }`
js

The provided object is first converted to an array of Arrays consisting of the key followed by its value for each of its key-value pairs using Object.entries().

This new array is then filtered with the callback passed in parameter which in our case excludes all the values which are not numbers.

The filtered array is then converted back into an object via fromEntries() which is the opposite of entries() converting array of arrays of key-value pairs into an object giving us objNumbersOnly filtered according to our conditions, i.e. an object with only keys where values are numbers!

Conclusion

The final snippet in a compact expression :

function objectFilter(obj, func = ([, val]) => val) {
  return Object.fromEntries(Object.entries(obj).filter(func));
}
js

Last updated: October 26, 2022

⚡ Who am i to talk about this? ⚡

Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.

Feel free to me through this learning journey by providing any feedback and if you wanna support me: