Filtering objects as easily as arrays.
Tags: javascript
Published: 2023-06-05 07:51:03

---
title: Filtering objects as easily as arrays.
published: true
date: 2022-10-26 00:00:00 UTC
tags: Javascript
canonical_url: https://blog.melvinvmegen.com/snippets/objectfilter
---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgj3onlhgxxi2sdld0z9.png)

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

## 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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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

```js
// 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 }
```

## Explanation

This function takes two parameters, an object to be filtered and an optional callback function which will be provided to [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.

```js
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 }`
```

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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ? 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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) which is the opposite of [entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/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 :

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