Home >Web Front-end >JS Tutorial >How to Filter JavaScript Objects Without Modifying the Native Prototype?
Object Filtering in JavaScript Using Prototype Extension
ECMAScript 5 introduced the filter() method for Array types, but not for Object types. This raises the question of how to implement a filter() method for Objects in JavaScript.
Custom Object Filter Implementation
One approach is to extend the Object.prototype with a custom filter() method:
Object.prototype.filter = function (predicate) { var result = {}; for (var key in this) { if (this.hasOwnProperty(key) && !predicate(this[key])) { result[key] = this[key]; } } return result; };
This implementation uses a loop to iterate over the object's own properties and checks if the predicate function returns true or false for each value. If false, the key-value pair is added to the result object.
However, extending the native Object.prototype is considered bad practice, as it can lead to conflicts with other libraries or code.
Alternative Approaches
Instead of extending Object.prototype, there are several alternative approaches to filtering objects in JavaScript:
Object.filter = (obj, predicate) => Object.keys(obj) .filter((key) => predicate(obj[key])) .reduce((res, key) => (res[key] = obj[key], res), {});
Object.filter = (obj, predicate) => { const filteredValues = Object.keys(obj).map((key) => { if (predicate(obj[key])) { return [key, obj[key]]; } }).filter(Boolean); return Object.fromEntries(filteredValues); };
Object.filter = (obj, predicate) => { const filteredEntries = Object.entries(obj).filter( ([key, value]) => predicate(value) ); return Object.fromEntries(filteredEntries); };
Example Usage
Let's filter an object using one of these alternative approaches:
const scores = { John: 2, Sarah: 3, Janet: 1 }; // Using the `reduce` and `Object.keys` approach: const filteredScores = Object.filter(scores, (score) => score > 1); console.log(filteredScores); // { Sarah: 3 }
By using these alternative methods, you can filter objects in JavaScript without extending the native prototype.
The above is the detailed content of How to Filter JavaScript Objects Without Modifying the Native Prototype?. For more information, please follow other related articles on the PHP Chinese website!