How to get _.pick functionality in lodash 4 version

This answer , shown below, is now, as far as I can tell, now broken into lodash v4.

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?

+5
source share
3 answers

Update (February 08)

Since v4.0.1, _.omitBy and _.pickBy now provide a key parameter for the predicate. Therefore, the correct answer is:

Use _.pickBy(object, [predicate=_.identity])

Original answer

Starting with v4, some methods have been split. For example, _.pick () is broken into _.pick(array, [props]) and _.pickBy(object, [predicate=_.identity])

My first approach was trying to use this _.pickBy() method. Unfortunately, all methods ...By() are only passed as the first argument. They will not receive a key or collection. That's why this does not work, just switching from _.pick() to _.pickBy() .

However, you can do it as follows:

 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) 
+2
source

Hm, it is not indicated that _. startWith () has been removed from Lodash.

Anyway, how about parsing the first character of a key?

 var result = _.pick(thing, function(value, key) { return key[0] == "a"; }); 
0
source
 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 working with the rest of the API. when you create an object from req.body parsing, 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 can see, this is a headache and looks ugly. Instead

 const user=new User(_.pick(req.body,["name","email","password","age"])) 
0
source

Source: https://habr.com/ru/post/1240695/


All Articles