Skip to content

Underscore could use a _.propertyResult #2286

Open
@machineghost

Description

@machineghost

The new _.property is really neat, and I love using it, but there's one problem: it only returns static values.

For instance, let's say I want to find out if any object in an array contains has an isNew property; I can do the following:

var objects = [{isNew: true}, {isNew: false}];

_(objects).any(_('isNew').property()); // === true

That's a lot better than before property, when I had to do:

_(objects).any(function(x) { return x.isNew; });

But what if instead of random objects I have a bunch of Backbone.Model objects. Those don't have an isNew property, they have an isNew method. So:

_(objects).any(_('isNew').property());

won't work; instead I'm back to the old style:

_(objects).any(function(x) { return _(x).result('isNew'); });

or (if I combine partial and result):

_(objects).any(function(_(_.result).partial(_, 'isNew'));

It would be really great if there was a method that was just like _.property, except that if it would return a function, it returns the result of executing that function instead (like _.result). In other words, if I could do ...

_(objects).any(_('isNew').propertyResult());

Since it's a fairly common practice to have is* methods on objects, and also common practice to want to use Underscore methods like any or filter with those methods, I really think this would be a useful addition to the library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    contribprobably belongs in Underscore-contribenhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions