In JavaScript, objects do not have a built-in filter() method like arrays. However, we can implement similar functionality by filtering an object's key-value pairs based on a specific condition.
- Use Object.entries() to convert an object into key-value pairs.
- Use Array.filter() to select the required properties.
- Use Object.fromEntries() to convert the filtered pairs back into an object.
- Use reduce() to implement a custom object filtering function.
Approach 1: Using Object.entries() and Object.fromEntries()
The idea is to convert the object into an array of key-value pairs using Object.entries(). We then use filter() to select the properties that satisfy the given condition and finally use Object.fromEntries() to create a new object from the filtered pairs.
Example: Filters the properties whose values are greater than 20.
let employees = {
Tony: 25,
Peter: 18,
Bruce: 30,
Clark: 20
};
// Filter properties based on their values
let filtered = Object.fromEntries(
Object.entries(employees)
.filter(([key, value]) => value > 20)
);
console.log(filtered);
Output
{ Tony: 25, Bruce: 30 }
Approach 2: Using reduce()
The idea is to use reduce() to iterate through the object's key-value pairs and add only those properties that satisfy the given condition to a new object.
Example: Filters employees belonging to the "IT" department.
let employees = {
Tony: "IT",
Peter: "HR",
Bruce: "IT",
Clark: "Editing"
};
// Function to filter object properties
function objectFilter(obj, predicate) {
return Object.entries(obj).reduce(
(result, [key, value]) => {
if (predicate(value, key)) {
result[key] = value;
}
return result;
}, {});
}
// Filter properties with value "IT"
let filtered = objectFilter(
employees,
value => value === "IT"
);
console.log(filtered);
Output
{ Tony: 'IT', Bruce: 'IT' }
Approach 3: Using a Custom filterObject() Function
The idea is to create a reusable function that accepts an object and a condition. The function converts the object into key-value pairs, filters them according to the condition, and returns the matching properties as a new object.
Example: Filters properties whose values are greater than 50.
let marks = {
Math: 85,
English: 45,
Science: 72,
History: 40
};
// Function to filter object properties
function filterObject(obj, predicate) {
return Object.fromEntries(
Object.entries(obj).filter(
([key, value]) => predicate(value, key)
)
);
}
// Filter values greater than 50
let result = filterObject(
marks,
value => value > 50
);
console.log(result);
Output
{ Math: 85, Science: 72 }
Note: The filter() method is directly available for arrays, not objects. For an object,
Object.entries()can be combined with filter() andObject.fromEntries()to achieve similar functionality.