DEV Community

Melvinvmegen
Melvinvmegen

Posted on • Originally published at blog.melvinvmegen.com on

Filtering objects as easily as arrays.

Image description

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

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, it 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 }
Enter fullscreen mode Exit fullscreen mode

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.

Note that: By default our function will filter out every falsy values and their paired key from the provided object but we can override that to our needs.

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 }`
Enter fullscreen mode Exit fullscreen mode

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.

Have you noticed that we were using destructuring assignement ? It allows us to take the first element of every array and store it in a variable called key, same for the second element value.

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));
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)