Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upSupport (or example) for `_.pick` #338
Comments
|
Probably the issue you've hit is covered by https://stackoverflow.com/questions/25769121/lo-dash-help-me-understand-why-pick-doesnt-work-the-way-i-expect As an alternative you could try one of the approaches below. Both approaches produce...
Note to create an easily reproduceable example I'm using lodash chain directly around a 'database' data structure. This is equivalent to what lowdb does, so use Lodash chaining documentation and examples as a reference if you hit similar issues. The first approach relies on modern destructuring but contains duplicate property names. The second approach avoids duplicating. lodash = require("lodash")
lodash.chain(
{
users: [
{ id: "spiderman", first: "peter", last: "parker" },
{ id: "superman", first: "clark", last: "kent" },
{ id: "batman", first: "bruce", last: "wayne" },
{ id: "wonderwoman", first: "diana", last: "prince" },
]
})
.get("users")
.filter(record => !record.id.includes("woman"))
.map(({ first, last }) => ({ first, last }))
.value() lodash = require("lodash")
lodash.chain(
{
users: [
{ id: "spiderman", first: "peter", last: "parker" },
{ id: "superman", first: "clark", last: "kent" },
{ id: "batman", first: "bruce", last: "wayne" },
{ id: "wonderwoman", first: "diana", last: "prince" },
]
})
.get("users")
.filter(record => !record.id.includes("woman"))
.map(record => lodash.pick(record, ["first","last"]))
.value() |
|
This is one way to do what you want db._.mixin({
pick2: function(arr, items) {
for (let i = 0; i < arr.length; i++) {
for (let key in arr[i]) {
if(items.indexOf(key) === -1){
delete arr[i][key];
}
}
}
return arr;
}
})
db.get('users')
.filter({ first: 'John' })
.pick2(['first', 'last'])
.value() |
I'm putting together a little GraphQL example I would like to use lowdb. Part of what I would like to do is to show in a resolver that you normally use a projection in Mongo or select in SQL to only get the data you want. With lowdb I thought I could use
_.picklike this https://lodash.com/docs/4.17.11#pickI could just be using it wrong. However if this is something that doesn't currently exist and could be implemented I'd be happy to give it a shot.