First of all, it's considered bad practice to extend Object.prototype. Instead, provide your feature as stand-alone function, or if you really want to extend a global, provide it as utility function on Object, just like there already are Object.keys, Object.assign, Object.is, ...etc.

I provide here several solutions:

  1. Using reduce and Object.keys
  2. As (1), in combination with Object.assign
  3. Using map and spread syntax instead of reduce
  4. Using Object.entries and Object.fromEntries

1. Using reduce and Object.keys

With reduce and Object.keys to implement the desired filter (using ES6 arrow syntax):

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

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

Note that in the above code predicate must be an inclusion condition (contrary to the exclusion condition the OP used), so that it is in line with how Array.prototype.filter works.

2. As (1), in combination with Object.assign

In the above solution the comma operator is used in the reduce part to return the mutated res object. This could of course be written as two statements instead of one expression, but the latter is more concise. To do it without the comma operator, you could use Object.assign instead, which does return the mutated object:

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

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

3. Using map and spread syntax instead of reduce

Here we move the Object.assign call out of the loop, so it is only made once, and pass it the individual keys as separate arguments (using the spread syntax):

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

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

4. Using Object.entries and Object.fromEntries

As the solution translates the object to an intermediate array and then converts that back to a plain object, it would be useful to make use of Object.entries (ES2017) and the opposite (i.e. create an object from an array of key/value pairs) with Object.fromEntries (ES2019).

It leads to this "one-liner" method on Object:

Object.filter = (obj, predicate) => 
                  Object.fromEntries(Object.entries(obj).filter(predicate));

// Example use:
var scores = {
    John: 2, Sarah: 3, Janet: 1
};

var filtered = Object.filter(scores, ([name, score]) => score > 1); 
console.log(filtered);

The predicate function gets a key/value pair as argument here, which is a bit different, but allows for more possibilities in the predicate function's logic.

Answer from trincot on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › filter
Array.prototype.filter() - JavaScript | MDN
The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Top answer
1 of 16
474

First of all, it's considered bad practice to extend Object.prototype. Instead, provide your feature as stand-alone function, or if you really want to extend a global, provide it as utility function on Object, just like there already are Object.keys, Object.assign, Object.is, ...etc.

I provide here several solutions:

  1. Using reduce and Object.keys
  2. As (1), in combination with Object.assign
  3. Using map and spread syntax instead of reduce
  4. Using Object.entries and Object.fromEntries

1. Using reduce and Object.keys

With reduce and Object.keys to implement the desired filter (using ES6 arrow syntax):

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

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

Note that in the above code predicate must be an inclusion condition (contrary to the exclusion condition the OP used), so that it is in line with how Array.prototype.filter works.

2. As (1), in combination with Object.assign

In the above solution the comma operator is used in the reduce part to return the mutated res object. This could of course be written as two statements instead of one expression, but the latter is more concise. To do it without the comma operator, you could use Object.assign instead, which does return the mutated object:

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

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

3. Using map and spread syntax instead of reduce

Here we move the Object.assign call out of the loop, so it is only made once, and pass it the individual keys as separate arguments (using the spread syntax):

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

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

4. Using Object.entries and Object.fromEntries

As the solution translates the object to an intermediate array and then converts that back to a plain object, it would be useful to make use of Object.entries (ES2017) and the opposite (i.e. create an object from an array of key/value pairs) with Object.fromEntries (ES2019).

It leads to this "one-liner" method on Object:

Object.filter = (obj, predicate) => 
                  Object.fromEntries(Object.entries(obj).filter(predicate));

// Example use:
var scores = {
    John: 2, Sarah: 3, Janet: 1
};

var filtered = Object.filter(scores, ([name, score]) => score > 1); 
console.log(filtered);

The predicate function gets a key/value pair as argument here, which is a bit different, but allows for more possibilities in the predicate function's logic.

2 of 16
295

Never ever extend Object.prototype.

Horrible things will happen to your code. Things will break. You're extending all object types, including object literals.

Here's a quick example you can try:

    // Extend Object.prototype
Object.prototype.extended = "I'm everywhere!";

    // See the result
alert( {}.extended );          // "I'm everywhere!"
alert( [].extended );          // "I'm everywhere!"
alert( new Date().extended );  // "I'm everywhere!"
alert( 3..extended );          // "I'm everywhere!"
alert( true.extended );        // "I'm everywhere!"
alert( "here?".extended );     // "I'm everywhere!"

Instead create a function that you pass the object.

Object.filter = function( obj, predicate) {
    let result = {}, key;

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

    return result;
};
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Iterator › filter
Iterator.prototype.filter() - JavaScript | MDN
The filter() method of Iterator instances returns a new iterator helper object that yields only those elements of the iterator for which the provided callback function returns true.
🌐
MDN
mdn2.netlify.app › en-us › docs › web › javascript › reference › global_objects › array › filter
Array.prototype.filter() - JavaScript | MDN
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › filter-object
How to Filter an Object with JavaScript - Mastering JS
const obj = { name: 'Luke Skywalker', title: 'Jedi Knight', age: 23 }; // Convert `obj` to a key/value array // `[['name', 'Luke Skywalker'], ['title', 'Jedi Knight'], ...]` const asArray = Object.entries(obj); const filtered = asArray.filter(([key, value]) => typeof value === 'string'); // Convert the key/value array back to an object: // `{ name: 'Luke Skywalker', title: 'Jedi Knight' }` const justStrings = Object.fromEntries(filtered);
🌐
W3Schools
w3schools.com › jsref › jsref_filter.asp
JavaScript Array filter() Method
The filter() method creates a new array filled with elements that pass a test provided by a function.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › CSS › Reference › Properties › filter
filter - CSS | MDN
Filter functions are applied in order of appearance. The same filter function can be repeated. ... #MDN-logo { border: 1px solid blue; filter: drop-shadow(5px 5px 0 red) hue-rotate(180deg) drop-shadow(5px 5px 0 red); }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object
Object - JavaScript | MDN
Nearly all objects in JavaScript are instances of Object; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden).
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn › Tools_and_testing › Client-side_JavaScript_frameworks › Angular_filtering
Filtering our to-do items - Learn web development | MDN
The class binding, [class.active], applies the active class when the value of filter matches the expression. For example, when the user clicks the Done button, which sets the filter value to done, the class binding expression of filter === 'done' evaluates to true.
🌐
DigitalOcean
digitalocean.com › community › tutorials › js-filter-array-method
How To Use the filter() Array Method in JavaScript | DigitalOcean
August 26, 2021 - The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Functional Programming - Implement the filter Method on a Prototype
November 17, 2023 - Hello everyone, i want to know something, to make it clear, look at the code in the photo: I found this solution by FCC team, i want to know why did they wrote If (Boolean(callback(this[B], B, this))) and why exactly this order, for example why not write if (Boolean(callback(this[B], this, B))); Challenge Information: Functional Programming - Implement the filter Method on a Prototype
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › TypedArray › filter
TypedArray.prototype.filter() - JavaScript | MDN
The filter() method of TypedArray instances creates a copy of a portion of a given typed array, filtered down to just the elements from the given typed array that pass the test implemented by the provided function. This method has the same algorithm as Array.prototype.filter().
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › find
Array.prototype.find() - JavaScript | MDN
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6]; const firstTrough = numbers .filter((num) => num > 0) .find((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable.
🌐
freeCodeCamp
forum.freecodecamp.org › code feedback
Implement a Matching Object Filter - Contains Hints and Solution - Code Feedback - The freeCodeCamp Forum
January 28, 2026 - It took me a while, but after combing through the MDN docs. I was able to find a solution. Hints: Look into JSON static methods. Think about how you can manipulate strings so that you can compare the source object with the objects in the array. How can you use some built in Array methods to filter ...
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.filter()
JavaScript Array filter() Method
November 7, 2024 - The filter() method creates a new array with elements from the original array, which passes a test function. ... The currentElement is the current element in the array that is being processed by the callbackFn function.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › CanvasRenderingContext2D › filter
CanvasRenderingContext2D: filter property - Web APIs | MDN
The CanvasRenderingContext2D.filter property of the Canvas 2D API provides filter effects such as blurring and grayscaling. It is similar to the CSS filter property and accepts the same values.
🌐
Medium
medium.com › @melaniecp › filtering-an-arrays-objects-based-on-a-value-in-a-key-value-array-using-filter-and-includes-27268968308f
Filtering an array’s objects, based on a value in a key value array, using filter() and includes()…
April 8, 2019 - If it contains the value we’re looking for, in this case the integer 8 (for 8 years old), then it will keep that object for the new array because it returned true (meaning it passed the test). If we console.log(ageAppropriate), the array will only contain the activities that are appropriate for kids who are the age of 8. That’s it! To see a full code sample, go here. To read more about the filter() method, check out the MDN docs here.
🌐
Reddit
reddit.com › r/javascript › exploring a pattern that's growing in popularity: wtf is array.filter(boolean) doing?
r/javascript on Reddit: Exploring a pattern that's growing in popularity: WTF is array.filter(Boolean) doing?
November 13, 2021 - I've seen the filter(Boolean) in other places and now it's documented in a blog post and anyone can easily look up the behavior of Boolean on mdn. Built-in functions are rarely removed from the standard as well. ... the first time I saw this in my coworkwers pr my head exploded. i didnt object cause i have a ...thing with trying to pick my battles these days but my god