Hi,
Here is a common use-case for filter. Given
a = {35: true, 45: true, 55: false}
one would like to filter and get back only pairs which value is truish:
_.filter(a, function(val, key) {
val === true;
});
// => {35: true, 45: true}
Currently, functions such as filter push(value) so one gets an array.
Is there any easy way to achieve this with a workaround, and if not, would you consider switching the return's type based on whether we're providing an object or a list?
+1
I just needed the same thing and this issue was the 2nd Google git I got when searching. The only problem with making _.filter on objects return objects is backwards compatibility...
filter
is a function that originates in ES5 ... and we certainly don't want to break basic compatibility with the spec.
To address the bigger picture: All Underscore.js enumerable function can take either objects or arrays, and all return arrays. Breaking consistency here would need to be done for all of the functions at once, not just one of them. The current API allows you to compose Underscore functions without having to worry about the input types.
I've added filter and reject functions to this mixin gist tracking map functions for objects w/ key/val persistence:
+1
+1 Could you guys add _.filterObj
(etc) one at a time, similar to _.mapObj
?
jk, just saw _.pick
which is perfect for my use case
@jtfairbank exactly what I need and probably what most people need when they come here looking to 'filter' an object and create an object.
Most helpful comment
jk, just saw
_.pick
which is perfect for my use case