Lo-Dash - Help me understand why _.pick is not working as I expect

It works:

MyCollection.prototype.select = function (properties) {
   var self = this;

   return {
      where: function (conditions) {
         return _.chain(self.arrayOfObjects)
           .where(conditions)
           .map(function (result) {
              return _.pick(result, properties);
           })
           .value();
      }
   };
};

      

Lets me query my collection like so:

var people = collection
             .select(['id', 'firstName'])
             .where({lastName: 'Mars', city: 'Chicago'});

      

I expected to be able to write code like this:

MyCollection.prototype.select = function (properties) {
   var self = this;

   return {
      where: function (conditions) {
         return _.chain(self.arrayOfObjects)
           .where(conditions)
           .pick(properties);
           .value();
      }
   };
};

      

The Lo-Dash documentation specifies the callback _.pick

as "[callback] (function | ... string | string []): function called for each iteration, or property names to select, specified as individual property names or arrays of property names." This led me to believe that I can just provide an array of properties that will apply to every element in arrayOfObjects

that satisfies the conditions. What am I missing?

+3


source to share


2 answers


http://lodash.com/docs#pick

It expects Object

as the first parameter you give it Array

.

Arguments

1. object (Object): The source object.
2. ...
3. ...

      



I think this is the best you can do:

MyCollection.prototype.select = function (properties) {
   var self = this;

   return {
      where: function (conditions) {
         return _.chain(self.arrayOfObjects)
           .where(conditions)
           .map(_.partialRight(_.pick, properties))
           .value();
      }
   };
};

      

+5


source


This doesn't work because it _.pick

expects an object, not a collection, which is going through a function where

in your chain.



+2


source







All Articles