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
Release: 2024-11-11 20:46:03
Original
467 people have browsed it

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

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

2. Map and Spread Syntax

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

3. Object.assign

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

Example Usage

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

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

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

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!

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