Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get _.pick functionality in lodash version 4

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?

like image 351
SDK Avatar asked Oct 30 '22 11:10

SDK


1 Answers

Update (08. February)

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])

Original Answer

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)
like image 102
NicBright Avatar answered Nov 12 '22 14:11

NicBright