This answer, shown below, is now broken in lodash v4 as far as I can tell.
var thing = {
"a": 123,
"b": 456,
"abc": 6789
};
var result = _.pick(thing, function(value, key) {
return _.startsWith(key, "a");
});
console.log(result.abc) // 6789
console.log(result.b) // undefined
How do you do this in version 4 of lodash?
Since v4.0.1, _.omitBy and _.pickBy now provide a key param to the predicate. Therefore, the correct answer now is:
Use _.pickBy(object, [predicate=_.identity])
Starting with v4, some methods have been split. For Example, _.pick() has been split into _.pick(array, [props])
and _.pickBy(object, [predicate=_.identity])
My first approach was trying this _.pickBy()
method. Unfortunately all ...By()
methods are only passed the value as the first argument. They won't get the key or the collection passed. That's why it does not work by simply switching from _.pick()
to _.pickBy()
.
However, you can do it like this:
var thing = {
"a": 123,
"b": 456,
"abc": 6789
};
var result = _.pick(thing, _(thing).keys().filter(function(key) {
return _.startsWith(key, "a");
}).value());
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With