title: JavaScript: filter() for Objects
body: <p>ECMAScript 5 has the <code>filter()</code> prototype for <code>Array</code> types, but not <code>Object</code> types, if I understand correctly.</p>
  
  <p>How would I implement a <code>filter()</code> for <code>Object</code>s in JavaScript? </p>
  
  <p>Let's say I have this object:</p>
  
  <pre><code>var foo = {
      bar: "Yes"
  };
  </code></pre>
  
  <p>And I want to write a <code>filter()</code> that works on <code>Object</code>s:</p>
  
  <pre><code>Object.prototype.filter = function(predicate) {
      var result = {};
  
      for (key in this) {
          if (this.hasOwnProperty(key) &amp;&amp; !predicate(this[key])) {
              result[key] = this[key];
          }
      }
  
      return result;
  };
  </code></pre>
  
  <p>This works when I use it in the following demo, 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.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>Object.prototype.filter = function(predicate) {
    var result = {};
    for (key in this) {
      if (this.hasOwnProperty(key) &amp;&amp; !predicate(this[key])) {
        console.log("copying");
        result[key] = this[key];
      }
    }
    return result;
  };
  
  var foo = {
    bar: "Yes",
    moo: undefined
  };
  
  foo = foo.filter(function(property) {
    return typeof property === "undefined";
  });
  
  document.getElementById('disp').innerHTML = JSON.stringify(foo, undefined, '  ');
  console.log(foo);</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>#disp {
    white-space: pre;
    font-family: monospace
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="disp"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>