5

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?

Community
  • 1
  • 1
SDK
  • 820
  • 1
  • 12
  • 24

3 Answers3

2

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)
NicBright
  • 7,289
  • 5
  • 18
  • 19
  • Yup I tried the same thing, using _.pick and _.pickBy chaining - without success. I'll give you one for ingenuity - but can't really accept as an elegant answer. To my mind they've actually removed functionality. – SDK Jan 17 '16 at 10:08
0

Hm, there is not documented that _.startsWith() has been removed from Lodash.

One way or another, how about parsing the first character of the key?

var result = _.pick(thing, function(value, key) {
  return key[0] == "a";
});
vorillaz
  • 6,098
  • 2
  • 30
  • 46
  • _.pick() in v4 does no longer accept a predicate. That's what _.pickBy is now doing. See my answer for more details. – NicBright Jan 16 '16 at 10:46
0
var thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

_.pick(object, arrayOfProperties)
_.pick(thing,["a","b"])={"a":123,"b":456}

this method is very useful when you work with rest API. when you create an object from parsing req.body this is how we create the object.

router.post("/users", async (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    age: req.body.age
  });});

as you see this is headache and looks ugly. Instead

const user=new User(_.pick(req.body,["name","email","password","age"]))
Yilmaz
  • 35,338
  • 10
  • 157
  • 202