Home >Web Front-end >JS Tutorial >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), {}); };
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 }), {}); };
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)) ); };
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!