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 an object based on an array JavaScript
Let's say we have an array and an object like this:
const arr = ['a', 'd', 'f'];
const obj = {
"a": 5,
"b": 8,
"c": 4,
"d": 1,
"e": 9,
"f": 2,
"g": 7
};
We are required to write a function that takes in the object and the array and filter away all the object properties that are not an element of the array. So, the output should only contain 3 properties, namely: "a", "d" and "f".
Method 1: Using delete Operator (Modifies Original)
This approach modifies the original object by deleting unwanted properties:
const arr = ['a', 'd', 'f'];
const obj = {
"a": 5,
"b": 8,
"c": 4,
"d": 1,
"e": 9,
"f": 2,
"g": 7
};
const filterObject = (obj, arr) => {
Object.keys(obj).forEach((key) => {
if(!arr.includes(key)){
delete obj[key];
}
});
};
filterObject(obj, arr);
console.log(obj);
{ a: 5, d: 1, f: 2 }
Method 2: Using Object.keys() and reduce() (Creates New Object)
This approach creates a new filtered object without modifying the original:
const arr = ['a', 'd', 'f'];
const obj = {
"a": 5,
"b": 8,
"c": 4,
"d": 1,
"e": 9,
"f": 2,
"g": 7
};
const filterObject = (obj, arr) => {
return Object.keys(obj)
.filter(key => arr.includes(key))
.reduce((result, key) => {
result[key] = obj[key];
return result;
}, {});
};
const filteredObj = filterObject(obj, arr);
console.log(filteredObj);
console.log("Original unchanged:", obj);
{ a: 5, d: 1, f: 2 }
Original unchanged: { a: 5, b: 8, c: 4, d: 1, e: 9, f: 2, g: 7 }
Method 3: Using Object.entries() and Object.fromEntries()
A more modern approach using ES2019 features:
const arr = ['a', 'd', 'f'];
const obj = {
"a": 5,
"b": 8,
"c": 4,
"d": 1,
"e": 9,
"f": 2,
"g": 7
};
const filterObject = (obj, arr) => {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => arr.includes(key))
);
};
const filteredObj = filterObject(obj, arr);
console.log(filteredObj);
{ a: 5, d: 1, f: 2 }
Comparison
| Method | Modifies Original | Performance | Browser Support |
|---|---|---|---|
| delete operator | Yes | Good | All browsers |
| filter + reduce | No | Good | ES5+ |
| Object.fromEntries | No | Best | ES2019+ |
Conclusion
Use the delete operator method when you want to modify the original object. For immutable filtering, prefer Object.fromEntries() for cleaner code or filter + reduce for better browser compatibility.
Advertisements
