Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-13 12:13:02
Original
770 people have browsed it

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

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

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

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

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!

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