这个有效:
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
中满足条件的每个项目。我错过了什么?
最佳答案
它需要一个 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/