Home >Web Front-end >JS Tutorial >How Can I Filter Properties in a JavaScript Object?

How Can I Filter Properties in a JavaScript Object?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 20:46:03384browse

How Can I Filter Properties in a JavaScript Object?

JavaScript filter() Method for Objects

While the Array type has the filter() method, the Object type does not. This article aims to provide a solution for implementing such a method.

Custom Object Filter Implementation

One approach involves extending the Object.prototype:

Object.prototype.filter = function(predicate) {
    var result = {};

    for (key in this) {
        if (this.hasOwnProperty(key) && !predicate(this[key])) {
            result[key] = this[key];
        }
    }

    return result;
};

Alternative Solutions

However, extending global prototypes is generally discouraged. Instead, consider these alternatives:

1. 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), {});

2. Map and Spread Syntax

Object.filter = (obj, predicate) =>
    Object.fromEntries(
        Object.entries(obj)
            .filter(([key, value]) => predicate(value))
            .map(([key, value]) => [key, value])
    );

3. Object.assign

const filter = (obj, predicate) =>
    Object.assign(
        {},
        ...Object.keys(obj)
            .filter(key => predicate(obj[key]))
            .map(key => ({[key]: obj[key]}))
    );

Example Usage

var foo = { bar: "Yes", moo: undefined };

var filtered = Object.filter(foo, property => typeof property === "undefined");

console.log(filtered); // { moo: undefined }

The above is the detailed content of How Can I Filter Properties in a JavaScript Object?. 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