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
Release: 2024-11-27 11:47:11
Original
534 people have browsed it

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;
};
Copy after login

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), {});
Copy after login
  • 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);
};
Copy after login
  • Using Object.entries and Object.fromEntries:
Object.filter = (obj, predicate) => {
    const filteredEntries = Object.entries(obj).filter(
        ([key, value]) => predicate(value)
    );

    return Object.fromEntries(filteredEntries);
};
Copy after login

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 }
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template