Home >Web Front-end >JS Tutorial >How to Implement a Custom `filter()` Method for Objects in JavaScript?

How to Implement a Custom `filter()` Method for Objects in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 12:13:02879browse

How to Implement a Custom `filter()` Method for Objects in JavaScript?

JavaScript: Implementing a Custom filter() Method for Objects

The ECMAScript 5 specification introduces the filter() prototype for arrays, but not for objects. Extending JavaScript's built-in objects is generally discouraged. However, if desired, one can create custom filter() functionality for objects using the following approaches:

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

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

2. Using reduce() and Object.keys() with Object.assign()

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

// Example: same as above

3. Using map() and spread syntax

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

// Example: same as above

4. Using Object.entries() and Object.fromEntries()

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

// Example: same as above

Remember, extending built-in prototypes can have unintended consequences. It's generally preferable to provide custom functions as stand-alone utilities or extend global objects specifically for specific functionality.

The above is the detailed content of How to Implement a Custom `filter()` Method for Objects in JavaScript?. 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