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;
};
๐ŸŒ
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, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-implement-a-filter-for-objects-in-javascript
Implement a filter() for Objects in JavaScript - GeeksforGeeks
October 14, 2025 - Use Array.prototype.reduce() to filter objects by accumulating only those elements that meet specific conditions into a new array.
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ filter-in-python
filter() in python - GeeksforGeeks
This simple example shows how to keep only the words starting with the letter 'a' from a list of fruits. ... def starts_a(w): return w.startswith("a") li = ["apple", "banana", "avocado", "cherry", "apricot"] res = filter(starts_a, li) print(list(res)) ...
Published ย  September 1, 2025
๐ŸŒ
MuleSoft
docs.mulesoft.com โ€บ dataweave โ€บ latest โ€บ dw-core-functions-filterobject
filterObject | MuleSoft Documentation
%dw 2.0 output application/json --- {"a" : "apple", "b" : "banana"} filterObject ((value) -> value == "apple") ... This example only outputs an object if the key starts with "letter". The DataWeave startsWith function returns true or false.
๐ŸŒ
sebhastian
sebhastian.com โ€บ javascript-filter-object
JavaScript filter object type tutorial | sebhastian
May 12, 2021 - Now that you have an array representing the object, you can use the Array.filter() method to filter this array. For example, the code below will remove an element with the key "Jack" and return the rest:
Find elsewhere
๐ŸŒ
jQuery
api.jquery.com โ€บ filter
.filter() | jQuery API Documentation
Select all divs and filter the selection with a jQuery object, keeping only the one with an id of "unique".
๐ŸŒ
Built In
builtin.com โ€บ software-engineering-perspectives โ€บ javascript-filter
How to Filter a JavaScript Array With the Filter() Method | Built In
In the above code, we defined an array of objects freelancers. We used the filter() method on the freelancers array and passed a function that checks if each freelancer is skilled in JavaScript.
๐ŸŒ
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 - Thereโ€™s an empty slot in the acc for the productId so Iโ€™ll add a .filter to the end of the .reduce so that any items that are null are removed from the acc.
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ javascript array methods โ€บ array.prototype.filter()
JavaScript Array filter() Method
November 7, 2024 - Next, define the range object with two properties lower and upper: let range = { lower: 1, upper: 10, };Code language: JavaScript (javascript) Then, define an array of mixed data that contains numbers, strings, and undefined: let data = [10, 20, '30', 1, 5, 'JS', undefined];Code language: JavaScript (javascript) After that, call the filter() methods of the data array and pass in the isInRange() function and the rangeobject.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_filter.asp
Python filter() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... ages = [5, 12, 17, 18, 24, 32] def myFunc(x): if x < 18: return False else: return True adults = filter(myFunc, ages) for x in adults: print(x) Try it Yourself ยป
๐ŸŒ
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 - This can be done by simply negating the condition in the Array.prototype.filter() callback. const pick = (obj, arr) => Object.fromEntries(Object.entries(obj).filter(([k]) => arr.includes(k))); const omit = (obj, arr) => Object.fromEntries(Object.entries(obj).filter(([k]) => !arr.includes(k))); const obj = { a: 1, b: '2', c: 3 }; pick(obj, ['a', 'c']); // { 'a': 1, 'c': 3 } omit(obj, ['b']); // { 'a': 1, 'c': 3 }
Top answer
1 of 16
940

If you have a list of allowed values, you can easily retain them in an object using:

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];

const filtered = Object.keys(raw)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    obj[key] = raw[key];
    return obj;
  }, {});

console.log(filtered);

This uses:

  1. Object.keys to list all properties in raw (the original data), then
  2. Array.prototype.filter to select keys that are present in the allowed list, using
    1. Array.prototype.includes to make sure they are present
  3. Array.prototype.reduce to build a new object with only the allowed properties.

This will make a shallow copy with the allowed properties (but won't copy the properties themselves).

You can also use the object spread operator to create a series of objects without mutating them (thanks to rjerue for mentioning this):

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];

const filtered = Object.keys(raw)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    return {
      ...obj,
      [key]: raw[key]
    };
  }, {});

console.log(filtered);

For purposes of trivia, if you wanted to remove the unwanted fields from the original data (which I would not recommend doing, since it involves some ugly mutations), you could invert the includes check like so:

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];

Object.keys(raw)
  .filter(key => !allowed.includes(key))
  .forEach(key => delete raw[key]);

console.log(raw);

I'm including this example to show a mutation-based solution, but I don't suggest using it.

2 of 16
199

If you are OK with using ES6 syntax, I find that the cleanest way to do this, as noted here and here is:

const data = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const { item2, ...newData } = data;

Now, newData contains:

{
  item1: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

Or, if you have the key stored as a string:

const key = 'item2';
const { [key]: _, ...newData } = data;

In the latter case, [key] is converted to item2 but since you are using a const assignment, you need to specify a name for the assignment. _ represents a throw away value.

More generally:

const { item2, ...newData } = data; // Assign item2 to item2
const { item2: someVarName, ...newData } = data; // Assign item2 to someVarName
const { item2: _, ...newData } = data; // Assign item2 to _
const { ['item2']: _, ...newData } = data; // Convert string to key first, ...

Not only does this reduce your operation to a one-liner but it also doesn't require you to know what the other keys are (those that you want to preserve).

A simple utility function would look like this:

function removePropFromObject(obj, prop) {
  const { [prop]: _, ...rest } = obj
  return { ...rest }
}
Top answer
1 of 3
14
  1. Use var myKeys = Object.keys(myObject) to get the keys.
  2. Check if a myString exist in the array myKeys using native

    var matchingKey = myKeys.indexOf(myString) !== -1
    

    Processing an array? Use this:

    var matchingKeys = myKeys.filter(function(key){ return key.indexOf(myString) !== -1 });
    
  3. Get the value using myObject[matchingKey].

    Processing an array? Use this:

    var matchingValues = matchingKeys .map(function(key){ return myObject[key] });
    
  4. No need to check array-boundaries or sizes. It's 100% boundary-safe.

2 of 3
4

I think that the more important questions you need to be asking yourself wrt your code are:

  1. What am I really trying to accomplish? (Answering this question will ultimately resolve your uncertainty related to whether you need to create a new object every time or, maybe, modify in place etc.)
  2. Am I using the right data-structure for the task? Look, you've built your data-structure from hash-tables, each with a single key! Not only that, the same key repeats in every such hash-table! What would you lose if you used just the value from that hash-table instead of the entire hash-table?
  3. This has become a mantra, but it is as true as ever: Make It Work, Make It Right, Make It Fast. Do not optimize unless the profiler tells you to. And most certainly not before you are absolutely confident that you made it right.

As an example of how your data-structure could've been made different such as to allow you to make filtering more straightforward:

var types = {
    'integer':   'int', 
    'character': 'char',
    'float':     'float',
    'double':    'double',
    'string':    'str', 
    'boolean':   'bool'
};

function filterTypes(accepted) {
    var result = {};
    for (var type in types)
        if (accepted.indexOf(type) > -1) 
            result[type] = types[type];
    return result;
}
// filterTypes(['integer', 'float', 'double']);
// { integer: 'int',
//   float: 'float',
//   double: 'double' }

And this is all there is to it. I would also question the purpose of these types in JavaScript, but I assumed they aren't to be implemented in JavaScript, just some kind of labels for some other programming language.

Note, additionally, that since the types hash-table is relatively small, there is no point of copying the keys to check against into another hash-table (to achieve faster lookup instead of indexOf). With this number of types indexOf will most likely outperform hash-table lookup, even more importantly. It offers a simpler solution, which works with acceptable speed.

๐ŸŒ
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.

๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Filtering through an object and returning items through a filter
May 19, 2018 - 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 ...