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
Filter nested object by keys using JavaScript
When working with arrays of objects in JavaScript, you often need to filter them based on specific criteria. This article demonstrates how to filter an array of objects by checking if their title property contains any of the specified search terms.
Problem Statement
Suppose we have an array of objects like this:
const arr = [{
'title': 'Hey',
'foo': 2,
'bar': 3
}, {
'title': 'Sup',
'foo': 3,
'bar': 4
}, {
'title': 'Remove',
'foo': 3,
'bar': 4
}];
We need to write a JavaScript function that takes an array of objects as the first parameter and an array of search strings as the second parameter. The function should return a new array containing only those objects whose title property partially or fully matches any of the search strings.
Solution
Here's how we can implement this filtering functionality:
const arr = [{
'title': 'Hey',
'foo': 2,
'bar': 3
}, {
'title': 'Sup',
'foo': 3,
'bar': 4
}, {
'title': 'Remove',
'foo': 3,
'bar': 4
}];
const filterTitles = ['He', 'Su'];
const filterByTitle = (arr = [], titles = []) => {
let res = [];
res = arr.filter(obj => {
const { title } = obj;
return !!titles.find(el => title.includes(el));
});
return res;
};
console.log(filterByTitle(arr, filterTitles));
[ { title: 'Hey', foo: 2, bar: 3 }, { title: 'Sup', foo: 3, bar: 4 } ]
How It Works
The function works by:
- Using the
filter()method to iterate through each object in the array - Destructuring the
titleproperty from each object - Using
find()to check if any of the search terms exists in the title - The
includes()method performs partial string matching - The double negation
!!converts the result to a boolean value
Alternative Approach
Here's a more concise version using some() method:
const filterByTitleConcise = (arr = [], titles = []) => {
return arr.filter(obj =>
titles.some(searchTerm => obj.title.includes(searchTerm))
);
};
console.log(filterByTitleConcise(arr, filterTitles));
[ { title: 'Hey', foo: 2, bar: 3 }, { title: 'Sup', foo: 3, bar: 4 } ]
Key Points
-
filter()creates a new array with elements that pass the test -
includes()performs case-sensitive partial string matching -
some()returns true if at least one element satisfies the condition - The original array remains unchanged
Conclusion
This filtering technique is useful for implementing search functionality in web applications. The combination of filter(), some(), and includes() provides a clean and efficient way to filter nested objects by string matching.
