Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Underscore mixin with common iterator functions adapted to work with objects and maintain key/val pairs.
_.mixin({
// ### _.objMap
// _.map for objects, keeps key/value associations
objMap: function (input, mapper, context) {
return _.reduce(input, function (obj, v, k) {
obj[k] = mapper.call(context, v, k, input);
return obj;
}, {}, context);
},
// ### _.objFilter
// _.filter for objects, keeps key/value associations
// but only includes the properties that pass test().
objFilter: function (input, test, context) {
return _.reduce(input, function (obj, v, k) {
if (test.call(context, v, k, input)) {
obj[k] = v;
}
return obj;
}, {}, context);
},
// ### _.objReject
//
// _.reject for objects, keeps key/value associations
// but does not include the properties that pass test().
objReject: function (input, test, context) {
return _.reduce(input, function (obj, v, k) {
if (!test.call(context, v, k, input)) {
obj[k] = v;
}
return obj;
}, {}, context);
}
});
@eethann

This comment has been minimized.

Copy link
Owner Author

eethann commented Aug 23, 2012

@eethann

This comment has been minimized.

Copy link
Owner Author

eethann commented Sep 8, 2012

I added filter and reject, as per this issue: jashkenas/underscore#359.

And also because I needed it for the Drupal Backbone module.

@mikermcneil

This comment has been minimized.

Copy link

mikermcneil commented Sep 22, 2012

Nice

@Trylobot

This comment has been minimized.

Copy link

Trylobot commented Sep 3, 2013

Very useful, thank you

@mikermcneil

This comment has been minimized.

Copy link

mikermcneil commented Sep 8, 2013

+1 +1 +1
Can't even begin to describe how often I use these!!!

@jaredh159

This comment has been minimized.

Copy link

jaredh159 commented May 9, 2014

thanks for this

@Boycce

This comment has been minimized.

Copy link

Boycce commented Jun 16, 2014

Thanks dude.

@paulmelnikow

This comment has been minimized.

Copy link

paulmelnikow commented Nov 18, 2014

Hey, I'd like to package this. Can you add a license?

@paulmelnikow

This comment has been minimized.

Copy link

paulmelnikow commented Nov 23, 2014

Hey, just following up. Would you mind adding a license to this gist? Underscore uses MIT, or you could put it in the public domain. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.