Home >Web Front-end >JS Tutorial >How to Filter JavaScript Objects Without Modifying the Native Prototype?

How to Filter JavaScript Objects Without Modifying the Native Prototype?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 11:47:11536browse

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:

  • Using reduce and Object.keys:
Object.filter = (obj, predicate) =>
    Object.keys(obj)
        .filter((key) => predicate(obj[key]))
        .reduce((res, key) => (res[key] = obj[key], res), {});
  • Using map and spread syntax:
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);
};
  • Using Object.entries and Object.fromEntries:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn