JavaScript: filter() for Objects

Posted by AgileMeansDoAsLittleAsPossible on Stack Overflow See other posts from Stack Overflow or by AgileMeansDoAsLittleAsPossible
Published on 2011-02-21T22:42:25Z Indexed on 2011/02/21 23:25 UTC
Read the original article Hit count: 121

Filed under:
|

ECMAScript 5 has the filter() prototype for Array types, but not Object types, if I understand correctly.

How would I implement a filter() for Objects in JavaScript?

Let's say I have this object:

var foo = {
    bar: "Yes"
};

And I want to write a filter() that works on Objects:

Object.prototype.filter = function(predicate) {
    var result = {};

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

    return result;
};

This works when I use it in jsfiddle (http://jsfiddle.net/MPUnL/4/), but when I add it to my site that uses jQuery 1.5 and jQuery UI 1.8.9, I get JavaScript errors in FireBug.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery