Solve - object.filter is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Check out my new book

Solve - object.filter is not a function Error #

The "object.filter is not a function" error occurs because the filter method is not implemented on an object. To filter an object, use the Object.values() method to get an array of the object's values and call the filter() method on the array of values.

typeerror object filter is not a function

Here is an example of how the error occurs.

index.js
const obj = { user1: {id: 1, name: 'Alice'}, user2: {id: 2, name: 'Bob'}, user3: {id: 3, name: 'Charlie'}, }; // ⛔️ TypeError: object.filter is not a function const result = obj.filter(value => { return value.id === 2; });

To solve the error, use the Object.values method to get an array of the object's values and call the Array.filter method on the array.

index.js
const obj = { user1: {id: 1, name: 'Alice'}, user2: {id: 2, name: 'Bob'}, user3: {id: 3, name: 'Charlie'}, }; // 👇️ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ...] console.log(Object.values(obj)); const result = Object.values(obj).filter(value => { console.log(value); return value.id === 2; }); // 👇️ [{id: 2, name: 'Bob'}] console.log(result);

The Object.values method returns an array of the object's values, on which we can call the Array.filter method.

The filter method returns a new array, which only contains the elements that satisfy the condition implemented by the provided function.

However, if you only need a single object, which matches a condition instead of an array of objects, you can use the Array.find method.

index.js
const obj = { user1: {id: 1, name: 'Alice'}, user2: {id: 2, name: 'Bob'}, user3: {id: 3, name: 'Charlie'}, }; // 👇️ if you only need the object that matches the condition const found = Object.values(obj).find(value => { return value.id === 2; }); // 👇️ {id: 2, name: 'Bob'} console.log(found);

The find method returns the first element that satisfies the condition - in our case an object.

Note that if the callback function does not return a truthy value on any of the iteration, the find method returns undefined.
Use the search field on my Home Page to filter through my more than 3,000 articles.