I find the default Javascript extremely poor on useful functions. There are some nice libraries, but somehow I always need something I can't find. Currently, I'd need a method removing all matching properties from an object. And I really mean removing, not creating a filtered copy. I've found similar methods in both jquery and underscore, but no exact match.
That's a long introduction, why I want to give it a try. As both $
and _
are taken, I'm extending the Object.prototype
which should be fine. So this is the code:
function removeMatching(predicate) {
for (var key in this) {
if (!Object.prototype.hasOwnProperty.call(this, key)) continue;
if (predicate(key, this[key])) delete this[key];
};
};
Object.defineProperty(Object.prototype, 'removeMatching', {
value: removeMatching,
writable: false,
configurable: false,
enumerable: false
});
It's all gets enclosed in a closure to prevent namespace pollution. I don't care much about speed as this can be improved later (but tell me). I don't care about style (it's fixed) not about compatibility with old crap. I do care about all problems possible in modern browsers.
It's to be used like
var o = {a: 1, b: 2, c: 3};
o.removeMatching(function(k, v) {return k === "a" || v === 2});
// now o is {c: 3}
Object.defineProperty()
only exists in modern browsers, but I assume you already know that. – jfriend00 Jun 24 '14 at 21:29if (Object.prototype.removeMatching === undefined) { ... }
– pgraham Jun 25 '14 at 1:24