javascript - Lo-Dash - 帮助我理解为什么 _.pick 不能按我期望的方式工作

标签 javascript lodash

这个有效:

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();
      }
   };
};

它允许我像这样查询我的收藏:

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

不过,我希望能够编写这样的代码:

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

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

Lo-Dash 文档将 _.pick 回调指定为“[callback] (Function|…string|string[]): The function called per iteration or property names to pick, specified as individual属性名称或属性名称数组。”这使我相信我可以只提供属性数组,该数组将应用于 arrayOfObjects 中满足条件的每个项目。我错过了什么?

最佳答案

http://lodash.com/docs#pick

它需要一个 Object 作为第一个参数,你给它一个 Array

Arguments

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

我认为这是你能做的最好的:

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

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

关于javascript - Lo-Dash - 帮助我理解为什么 _.pick 不能按我期望的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769121/

相关文章:

javascript - Lodash中函数同步返回

javascript - React 期望一个赋值或函数调用,但看到一个表达式

javascript - 使用lodash将对象的嵌套数组排序出来

javascript - 搜索嵌套对象并返回整个路径

javascript - 如何在 Angular 4 中检查 isBrowser

javascript - 映射对象数组,然后映射这些对象中的另一个数组并消除重复项

javascript - 如何使用 lodash 按 ID 合并两个对象数组?

javascript - Jquery 元素过滤方法不起作用

javascript - 每秒动态更改背景图像

javascript - 定位多个相似项目组中的事件