Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including ofilter with all npm packages installed. Try it out:

var ofilter = require("ofilter")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

ofilter v0.1.0

Array.prototype.filter for objects.

ofilter

Similar to Array.prototype.filter, except that it works on objects, and returns an object.

Usage

ofilter(object, callback[, thisObject])

Parameters

object is the object you want to filter.

callback is a function that will be called for each key in object.

thisObject is an optional object to use for this inside callback.

var o = {
  a: {prop: 1},
  b: {prop: 'b'},
  c: {prop: 1}
},

filtered = ofilter(o, function (item) {
  return item.prop === 1;
});

ok(filtered.a && filtered.c,
  'should contain positive matches.'); // Pass

ok(!filtered.b,
  'should not contain negative matches.'); // Pass

Crazy talk

This (along with several other common functional iterators) really needs to be part of the JavaScript specification. I can't recommend actually extending the Object prototype, but if you use ofilter() enough, maybe eventually, if we all believe hard enough, it will magically appear in a future version of the ECMAScript specification.

if (!Object.prototype.filter) {
  Object.prototype.filter = function (callback, thisObject) {
    return ofilter(this, callback, thisObject);
  }
}

var obj = {a: 'a', b: 'b'};

var a = obj.filter(function (item) {
  return item === 'a';
});

t.same(a, {a: 'a'},
  'should work like Array.prototype.filter(). Come on, TC39!');

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free