Home > Web Front-end > JS Tutorial > How can I effectively filter the key-value pairs in a JavaScript object?

How can I effectively filter the key-value pairs in a JavaScript object?

Barbara Streisand
Release: 2024-11-24 07:04:11
Original
734 people have browsed it

How can I effectively filter the key-value pairs in a JavaScript object?

JavaScript: filter() for Objects

The filter() prototype exists for Array types in ECMAScript 5, but not for Object types. To implement a filter() function for Objects in JavaScript, you can use the following strategies:

1. Using reduce() and Object.keys()

This method utilizes reduce() to loop through the object's keys and Object.keys() to retrieve those keys. Then, it filters the keys based on a predicate function and returns a new object with the filtered key-value pairs:

Object.filter = (obj, predicate) => {
  Object.keys(obj)
    .filter(key => predicate(obj[key]))
    .reduce((res, key) => (res[key] = obj[key], res), {});
};
Copy after login

2. Using map() and Spread Syntax

A similar approach to (1), but instead of reduce(), you can use map() and the spread syntax (...) to create a new object:

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

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

This method uses Object.entries() to convert the object into an array of key-value pairs and then Object.fromEntries() to reconstruct the object after filtering:

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

4. Caveat: Avoid Extending Object.prototype

While these solutions provide functional filter() implementations for Objects, it's considered bad practice to extend Object.prototype directly. Instead, provide your filter function as a stand-alone utility function, similar to existing JavaScript global utility functions like Object.assign() and Object.keys().

The above is the detailed content of How can I effectively filter the key-value pairs 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