ArticleZip > Filter Array Of Objects Whose Any Properties Contains A Value

Filter Array Of Objects Whose Any Properties Contains A Value

In programming, working with arrays of objects is a frequent task for developers. A common challenge they face is filtering an array of objects based on a specific value that can be found in any of the object's properties. This task can be efficiently achieved using JavaScript. Let's explore how you can filter an array of objects based on this criterion step by step.

To begin, suppose you have an array of objects like this:

Javascript

const data = [
    { id: 1, name: 'Alice', age: 25 },
    { id: 2, name: 'Bob', age: 30 },
    { id: 3, name: 'Charlie', age: 22 }
];

Imagine you want to filter this array based on a value, say 'Alice', that could be present in any of the object properties. Here's how you can accomplish this using JavaScript:

Javascript

const searchValue = 'Alice';

const filteredData = data.filter(obj => {
    return Object.values(obj).some(val =>
        typeof val === 'string' && val.includes(searchValue)
    );
});

console.log(filteredData);

Let's break down the code snippet:

- We define our search value, in this case, 'Alice'.
- We use the `filter()` method on the `data` array and provide a filtering function that checks if any of the object's property values contain the search value using the `some()` method.
- The `Object.values()` method retrieves an array of the object's property values which we then iterate over using the `some()` method.
- In the callback function of `some()`, we ensure that the value is a string and check if it includes the `searchValue`.
- The objects in which the search value is found in at least one property are retained in the `filteredData` array.

When you run this code, the `filteredData` array will contain the objects from the original array that match the filtering criterion.

This approach provides a flexible and powerful way to filter an array of objects based on values present in any of their properties. You can easily adapt this code snippet to suit your specific requirements by changing the search value or the conditions within the filtering function.

By following these steps and understanding how to leverage JavaScript array methods effectively, you can efficiently filter arrays of objects based on values contained within their properties. This technique enhances your ability to manipulate and extract data from complex data structures in your web development projects.

×