Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Filter array of objects whose properties contains a value in JavaScript
Filtering an array of objects based on property values is a common task in JavaScript. This technique allows you to search through all properties of objects to find matches based on a keyword.
Sample Data
Let's start with an array of objects containing user information:
const arr = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}];
The Problem
We need to filter objects where any property contains a specific value. For example:
When searching "lea", return objects containing "lea" in any property When searching "italy", return objects containing "italy" in any property
Using Regular Expression Filter
The most flexible approach uses regular expressions for case-insensitive matching:
const arr = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}];
const filterByValue = (arr = [], query = '') => {
const reg = new RegExp(query, 'i');
return arr.filter((item) => {
let flag = false;
for (prop in item) {
if (reg.test(item[prop])) {
flag = true;
}
}
return flag;
});
};
console.log(filterByValue(arr, 'ita'));
[
{ name: 'Lea', country: 'Italy' },
{ name: 'John', country: 'Italy' }
]
Using Object.values() Method
A more modern approach using Object.values() for cleaner code:
const filterByValueModern = (arr = [], query = '') => {
const searchTerm = query.toLowerCase();
return arr.filter(item =>
Object.values(item).some(value =>
value.toString().toLowerCase().includes(searchTerm)
)
);
};
console.log(filterByValueModern(arr, 'lea'));
[
{ name: 'Lea', country: 'Italy' }
]
Comparison
| Method | Performance | Readability | Regex Support |
|---|---|---|---|
| for...in loop | Good | Medium | Yes |
| Object.values() | Good | High | No (can be added) |
Key Points
- Regular expressions provide case-insensitive matching with the 'i' flag
-
Object.values()creates cleaner, more readable code - Convert values to strings to handle different data types
- Use
some()to stop searching once a match is found
Conclusion
Both approaches effectively filter arrays of objects by property values. Choose the regular expression method for advanced pattern matching, or Object.values() for simpler, more readable code.
Advertisements
