This 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();
}
};
};
It allows me to query my collection like so:
var people = collection
.select(['id', 'firstName'])
.where({lastName: 'Mars', city: 'Chicago'});
I expected to be able to write the code like this, though:
MyCollection.prototype.select = function (properties) {
var self = this;
return {
where: function (conditions) {
return _.chain(self.arrayOfObjects)
.where(conditions)
.pick(properties);
.value();
}
};
};
Lo-Dash documentation specifies the _.pick
callback as "[callback] (Function|…string|string[]): The function called per iteration or property names to pick, specified as individual property names or arrays of property names." That led me to believe I could just supply the properties array, which would be applied to each item in arrayOfObjects
that meets the conditions. What am I missing?
This 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();
}
};
};
It allows me to query my collection like so:
var people = collection
.select(['id', 'firstName'])
.where({lastName: 'Mars', city: 'Chicago'});
I expected to be able to write the code like this, though:
MyCollection.prototype.select = function (properties) {
var self = this;
return {
where: function (conditions) {
return _.chain(self.arrayOfObjects)
.where(conditions)
.pick(properties);
.value();
}
};
};
Lo-Dash documentation specifies the _.pick
callback as "[callback] (Function|…string|string[]): The function called per iteration or property names to pick, specified as individual property names or arrays of property names." That led me to believe I could just supply the properties array, which would be applied to each item in arrayOfObjects
that meets the conditions. What am I missing?
2 Answers
Reset to default 7http://lodash./docs#pick
It expects an Object
as the first parameter, you're giving it an 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();
}
};
};
It doesn't work because _.pick
expects an object, not a collection which is being passed through from the where
function in your chain.