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 the properties of an object based on an array and get the filtered object JavaScript
In JavaScript, you often need to filter an object's properties based on specific criteria. This article shows how to create a filtered object containing only the properties whose keys appear in a given array.
Problem Statement
We need to write a function that takes an object and an array of string literals, then returns a new object containing only the key-value pairs where the key exists in the array.
For example: If the object is {"a": [], "b": [], "c": [], "d": []} and the array is ["a", "d"], the output should be:
{"a": [], "d": []}
Solution Approach
The solution involves iterating over the object's keys and checking if each key exists in the filter array. If it does, we add that key-value pair to a new object.
Example Implementation
const capitals = {
"usa": "Washington DC",
"uk": "London",
"india": "New Delhi",
"italy": "Rome",
"japan": "Tokyo",
"germany": "Berlin",
"china": "Shanghai",
"spain": "Madrid",
"france": "Paris",
"portugal": "Lisbon"
};
const countries = ["uk", "india", "germany", "china", "france"];
const filterObject = (obj, arr) => {
const newObj = {};
for (key in obj) {
if (arr.includes(key)) {
newObj[key] = obj[key];
}
}
return newObj;
};
console.log(filterObject(capitals, countries));
{
uk: 'London',
india: 'New Delhi',
germany: 'Berlin',
china: 'Shanghai',
france: 'Paris'
}
Alternative Methods
Using Object.keys() and reduce()
const filterObjectWithReduce = (obj, arr) => {
return Object.keys(obj)
.filter(key => arr.includes(key))
.reduce((result, key) => {
result[key] = obj[key];
return result;
}, {});
};
console.log(filterObjectWithReduce(capitals, countries));
{
uk: 'London',
india: 'New Delhi',
germany: 'Berlin',
china: 'Shanghai',
france: 'Paris'
}
Using Object.fromEntries()
const filterObjectWithEntries = (obj, arr) => {
return Object.fromEntries(
Object.entries(obj).filter(([key, value]) => arr.includes(key))
);
};
console.log(filterObjectWithEntries(capitals, countries));
{
uk: 'London',
india: 'New Delhi',
germany: 'Berlin',
china: 'Shanghai',
france: 'Paris'
}
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| for...in loop | Good | Fast | All browsers |
| Object.keys() + reduce() | Better | Medium | ES5+ |
| Object.fromEntries() | Best | Medium | ES2019+ |
Conclusion
All three methods effectively filter object properties based on an array. Choose the for...in loop for maximum compatibility, or Object.fromEntries() for the most concise modern approach.
