Home >Web Front-end >JS Tutorial >How can you implement a `filter()` method for JavaScript objects?

How can you implement a `filter()` method for JavaScript objects?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 03:26:01732browse

How can you implement a `filter()` method for JavaScript objects?

JavaScript: Implementing filter() for Objects

JavaScript provides the filter() prototype for Array types, but this functionality is absent for Object types. To address this limitation, let's explore how to create a filter() implementation specifically for objects.

Implementation:

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

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

  return result;
};

While this implementation works in isolation, adding it to a site using jQuery 1.5 and jQuery UI 1.8.9 may trigger JavaScript errors.

Alternative Solutions:

Instead of modifying the Object prototype, consider these standalone or utility functions:

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. Using map and spread syntax:

Object.filter = (obj, predicate) => 
  Object.entries(obj)
        .filter(([key, value]) => predicate(value))
        .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});

3. Using Object.entries and Object.fromEntries:

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

Example Usage:

var scores = {
  John: 2,
  Sarah: 3,
  Janet: 1
};
var filtered = Object.filter(scores, score => score > 1); 
console.log(filtered);

These alternative solutions provide a cleaner and more maintainable way to filter object properties while preserving the original object.

The above is the detailed content of How can you implement a `filter()` method for JavaScript objects?. 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