Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why _.pick(object, _.identity) in lodash returns empty Object?

I'm trying to move underscore to lodash. But this line of code baffles me.

On my current project we have this line of code.

obj = _.pick(obj, _.identity);

Which is pretty obvious that it's trying to delete empty property.

Now when I switch to lodash, the same line of code returns empty object for me.

I'm trying to figure why. How do I achieve the same effect in lodash?

I tried this on both lodash and underscore websites. They produce different results.

This is from lodash

var obj = {_v:'10.1', uIP:'10.0.0.0', _ts:'123'}
_.pick(obj, _.identity);
Object {}

This is from underscore

var obj = {_v:'10.1', uIP:'10.0.0.0', _ts:'123'}
_.pick(obj, _.identity);
Object {_v: "10.1", uIP: "10.0.0.0", _ts: "123"}
like image 388
toy Avatar asked Mar 12 '23 19:03

toy


1 Answers

Why _.pick(object, _.identity) in lodash returns empty Object?

Because pick in lodash expects an array of property names to be passed to it:

var object = { 'a': 1, 'b': '2', 'c': 3 };

_.pick(object, ['a', 'c']);
// → { 'a': 1, 'c': 3 }

How do I achieve the same effect in lodash?

Lodash has a method called pickBy which accepts a callback function:

var object = { 'a': 1, 'b': '2', 'c': 3 };

_.pickBy(object, _.isNumber);
// → { 'a': 1, 'c': 3 }
like image 152
Felix Kling Avatar answered Mar 24 '23 08:03

Felix Kling