Implementing filter() for JavaScript Objects

While ECMAScript 5 features a filter() method for Array objects, it seems there’s no such method for Object types. I’m curious about how to create a filter() function specifically for Objects in JavaScript. For instance, given the following object:

var sampleObject = { propertyOne: ‘Yes’ };
I’d like to write a filter() function that can be applied to objects, similar to the one below:
Object.prototype.filterProperties = function(condition) { var result = {}; for (const key in this) { if (this.hasOwnProperty(key) && !condition(this[key])) { result[key] = this[key]; } } return result; };
This implementation works in a demonstration, yet when added to my jQuery 1.5 and jQuery UI 1.8.9 project, it results in JavaScript errors appearing in FireBug. Any suggestions?

You can filter JavaScript objects by using Object.entries() to convert the object to an array, filter that array, and then convert it back to an object:

function filterObject(obj, callback) { return Object.fromEntries( Object.entries(obj).filter(([key, value]) => callback(key, value)) ); }

Example usage:

const myObj = { a: 1, b: 2, c: 3 }; const filteredObj = filterObject(myObj, (key, value) => value > 1); // filteredObj will be { b: 2, c: 3 }