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
Filtering of JavaScript object
Filtering JavaScript objects allows you to extract specific key-value pairs based on certain criteria. This is useful when working with large datasets or when you need to display only relevant information.
Problem Statement
We need to create a function that takes an object and a search string, then filters the object keys that start with the search string and returns a new filtered object.
Example: Basic Object Filtering
const obj = {
"PHY": "Physics",
"MAT": "Mathematics",
"BIO": "Biology",
"COM": "Computer Science",
"SST": "Social Studies",
"SAN": "Sanskrit",
"ENG": "English",
"HIN": "Hindi",
"ESP": "Spanish",
"BST": "Business Studies",
"ECO": "Economics",
"CHE": "Chemistry",
"HIS": "History"
};
const str = 'en';
const returnFilteredObject = (obj, str) => {
const filteredObj = {};
Object.keys(obj).forEach(key => {
if (key.substr(0, str.length).toLowerCase() === str.toLowerCase()) {
filteredObj[key] = obj[key];
}
});
return filteredObj;
};
console.log(returnFilteredObject(obj, str));
{ ENG: 'English' }
How It Works
The function iterates through each key of the object using Object.keys(). For each key, it extracts a substring of the same length as the search string and compares them (case-insensitive). If they match, the key-value pair is added to the filtered object.
Using Modern JavaScript Methods
Here's a more concise approach using Object.entries() and Object.fromEntries():
const filterObjectModern = (obj, str) => {
return Object.fromEntries(
Object.entries(obj).filter(([key]) =>
key.toLowerCase().startsWith(str.toLowerCase())
)
);
};
// Test with multiple prefixes
console.log(filterObjectModern(obj, 'b')); // Keys starting with 'b'
console.log(filterObjectModern(obj, 'c')); // Keys starting with 'c'
{ BIO: 'Biology', BST: 'Business Studies' }
{ COM: 'Computer Science', CHE: 'Chemistry' }
Filtering by Value
You can also filter objects based on their values instead of keys:
const filterByValue = (obj, searchValue) => {
return Object.fromEntries(
Object.entries(obj).filter(([key, value]) =>
value.toLowerCase().includes(searchValue.toLowerCase())
)
);
};
console.log(filterByValue(obj, 'science'));
{ COM: 'Computer Science' }
Comparison of Methods
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| forEach + manual object building | Good | Moderate | All browsers |
| Object.fromEntries + filter | Good | Excellent | ES2019+ |
Key Points
- Use
startsWith()instead ofsubstr()for better readability - Consider case-insensitive matching with
toLowerCase() - Modern methods like
Object.fromEntries()provide cleaner code - Choose between modifying the original object or creating a new one based on your needs
Conclusion
Object filtering in JavaScript can be accomplished using traditional iteration or modern functional methods. The choice depends on your browser support requirements and code style preferences.
