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
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;
};
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-implement-a-filter-for-objects-in-javascript
Implement a filter() for Objects in JavaScript - GeeksforGeeks
October 14, 2025 - In JavaScript, objects don’t have a built-in filter() method like arrays, but you can implement similar functionality manually.
Discussions

How to Filter Array of Objects by Value in JavaScript
Better explanation here: https://javascript.info/array-methods#filter or just use literally any one of these Underscore funcs: https://underscorejs.org/#collections Link farming is bad, kids... More on reddit.com
🌐 r/JavaScriptTips
1
6
April 14, 2023
Return object from filter when one of the values matches
I am working on a personal project where I have a dropdown filter that displays cards based on the category. Some cards have multiple category descriptions. I am trying to filter the results based off the select options. I am having trouble selecting any objects that contain the categories ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
August 24, 2023
Filtering through an object and returning items through a filter
Hi Everyone I am trying to write a function, when given a list of objects, returns the list of all active items. My array of objects would like like this const list = [ { id: 1, active: true }, … More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
May 19, 2018
Javascript + Filter object of values - Code Review Stack Exchange
I have the object with values. I trying to filter based on values. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
January 22, 2021
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › filter
Array.prototype.filter() - JavaScript | MDN
December 13, 2025 - 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.
🌐
Reddit
reddit.com › r/javascripttips › how to filter array of objects by value in javascript
r/JavaScriptTips on Reddit: How to Filter Array of Objects by Value in JavaScript
April 14, 2023 -

If you're working with arrays of objects in JavaScript, you may find yourself needing to filter the array based on a specific value. Luckily, JavaScript provides us with a built-in method to do just that: Array.filter() . In this article, we'll explore how to to filter an array of objects by value.

Let's say we have an array of objects representing different people, with properties like "name", "age", and "occupation". We want to filter this array to only include people who are over the age of 30. Here's how we could do it:

const people = [
  { name: "Alice", age: 25, occupation: "Engineer" },
  { name: "Bob", age: 35, occupation: "Teacher" },
  { name: "Charlie", age: 42, occupation: "Doctor" },
  { name: "Dave", age: 28, occupation: "Writer" },
];

const filteredPeople = people.filter((person) => person.age > 30);

console.log(filteredPeople);
// Output: [{ name: "Bob", age: 35, occupation: "Teacher" }, { name: "Charlie", age: 42, occupation: "Doctor" }]

Here, we're using the filter() method on the people array, and passing in a function as an argument. This function takes each object in the array as its argument (which we've named person), and returns a boolean value indicating whether that object should be included in the filtered array.

In this case, we're using a simple comparison to check if the person's age is greater than 30. If it is, the function returns true, and the person is included in the filtered array. If not, the function returns false, and the person is excluded.

This is just one example of how you can use Array.filter() to filter an array of objects by value. Depending on your specific use case, you may need to use more complex comparison logic or filter on different properties of the objects in the array. But with Array.filter( as your tool, you'll be able to filter your arrays with ease.

🌐
Scott Spence
scottspence.com › home › posts › reduce and filter javascript object on property
Reduce and Filter JavaScript Object on Property - Scott Spence
January 25, 2022 - How do you filter a JavaScript object that has duplicate properties? Use reduce! The specific situation I had is a list of objects with dupl...
Find elsewhere
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › filter object keys or values
Filter a JavaScript object's properties by keys or values - 30 seconds of code
January 14, 2024 - Learn how to transform objects by filtering their properties based on an array of keys or a predicate function.
🌐
Steveruiz
steveruiz.me › posts › how-to-filter-an-object
Filtering an Object in TypeScript - Steve Ruiz
August 3, 2021 - In JavaScript: function filterObject(obj, fn) { return Object.fromEntries(Object.entries(obj).filter(fn)); } It's a bit trickier in TypeScript: type Entry<T> = { [K in keyof T]: [K, T[K]]; }[keyof T]; function filterObject<T extends object>( ...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Filtering through an object and returning items through a filter - JavaScript - The freeCodeCamp Forum
May 19, 2018 - Hi Everyone I am trying to write a function, when given a list of objects, returns the list of all active items. My array of objects would like like this const list = [ { id: 1, active: true }, { id: 2, active: false }, { id: 3, active: true }, { id: 4, active: false } ]; I would like to return a new array of objects of only those marked activie: true like so: [ { id: 1, active: true }, { id: 3, act...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object
Object - JavaScript | MDN
Number, String, Boolean, Symbol, BigInt primitives are wrapped into their corresponding object wrappers. There are two ways to achieve nearly the same effect in JavaScript.
🌐
W3Schools
w3schools.com › jsref › jsref_filter.asp
JavaScript Array filter() Method
abort afterprint animationend animationiteration animationstart beforeprint beforeunload blur canplay canplaythrough change click contextmenu copy cut dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange ended error focus focusin focusout fullscreenchange fullscreenerror hashchange input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseover mouseout mouseup offline online open pagehide pageshow paste pause play playing progress ratechange resize reset scroll search seeked seeking select show stalled submit suspend timeupdate toggle touchcancel touchend touchmove touchstart transitionend unload volumechange waiting wheel HTML Event Objects
🌐
Supabase
supabase.com › docs › reference › javascript › using-filters
JavaScript: Using filters
2 days ago - Return data as a single object instead of an array of objects.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-filter-object-array-based-on-attributes
How to Filter Object Array based on Attributes? - GeeksforGeeks
July 23, 2025 - You can filter an array of objects based on attributes using the filter() method. Provide a callback function that evaluates each object, returning true to keep it or false to discard.
Top answer
1 of 2
1

Avoid use dictionary when you need Array

I'm not sure why you would prefer to store your Array-like data in a dictionary. I would suggest use a real Array if you need an Array.

Order of Object.keys

You may read more details about the order of Object.keys return values from this post: Does ES6 introduce a well-defined order of enumeration for object properties? The order of Object.keys is defined in ES2020. It may not work as you want in older environments.

Anyway, relay on the order of Object.keys don't seems to be a good idea to me. You may always sort the keys after Object.keys if you want though.

Use Object.assign to convert to / from Array

When you need an Array, use an Array. You can try Object.assign which convert your dictionary into Array and vice versa. (But this only applied to "when you cannot change the interface due to any reason").

function filterData(data, value) {
    const arrayData = Object.assign([], data.map);
    const filteredArrayData = arrayData.filter(list => list.includes(value));
    const result = Object.assign({}, filteredArrayData);
    return result;
}
2 of 2
0

Review

  • the whole filter chain could be on basis of value instead of key from data since there's no real use of key here

filter part

  • technically your approach is perfect, just that it could be concise/readable
  • you can simplify the filter as in below snippet, simply because readability is one of the TOP priority of a good code IMHO

map part

  • instead of juggling the same object inside reduce between all elements we can simply get the required objects out of it.

  • one other major thing is that reduce as the name suggests is for when you wish to reduce N elements into exactly 1 element by some logic, which clearly isn't the case here & thus i think map should be preferred.

  • we can use map here since at the end we want an array of objects, so here we can return object for each key which at end gets collected as array

  • apart from these the redability point again applies here as well, since this can also be simplified very much, refer the snippet to get an idea

  • quoting a point from Mozilla's doc on reduce

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

Alternate approach

const  data = {
  "map": {
    "0": ["abcd"],
    "1": ["efgh"],
    "2": ["xyz"],
    "3": ["abcd", "xyz"],
  }
}

const filtered = Object.values(data.map)
  .filter(value => value.includes('xyz'))
   // the () after the "=>" are used to wrap returned result into object
   // the [i] inside ({..}) is used for setting the key dynamically
  .map((value, i) => ({[i]: value}));
  
console.log('filtered', filtered);

  • The data structure seems to be object representation of array, so if possible prefer 2D array over object with 0 based keys, this would make things more simple

PS: answer is updated after useful suggestions of @Toby Speight & @Graipher in comments

🌐
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.
🌐
Code Highlights
code-hl.com › home › javascript › tutorials
Ultimate Guide: Filter Objects by Key Value in JavaScript | Code Highlights
February 1, 2024 - This function is versatile and can be used to filter objects by any key-value pair. Ensure your JavaScript knowledge is solid.
🌐
Stack Abuse
stackabuse.com › how-to-filter-an-object-by-key-in-javascript
How to Filter an Object by Key in JavaScript
March 17, 2022 - In this short article - we've taken a look at filtering objects by value, using the Object.keys() method, filtered via the filter() method.
🌐
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);
🌐
TutorialsPoint
tutorialspoint.com › how-to-filter-an-object-depending-on-the-field-s-value-in-javascript
How to filter an object depending on the field\'s value in JavaScript?
October 13, 2023 - An object in JavaScript is defined as a set of keyvalue pairs. It is used to define the properties of a single object. So to filter the object depending on the field's value can be achieved using JavaScript. By using the ifelse condition we can filter the object depending on the value.