简体   繁体   中英

Using lodash to pick defined values from an object

I'd like to pick defined values from an object according to an array of keys I supply.

Say I have an object like so:

{
  _id: '1234'
  status: 'complete',
  current_task: null,
  current_task_attempts: 2
}

I'd like to pick out the _id , status and current_task properties, but only if they are not null or undefined :

{
  _id: '1234'
  status: 'complete'
}

My current solution is:

_.pickBy(_.pick(obj, ['_id', 'status', 'current_task']))

But this feels a bit weird. Is there a single lodash function that can do what I want?

It's not a single function. However, you can try using a sequence, which does exactly the same thing you did, but is a bit more readable:

_(obj).pick(['_id', 'status', 'current_task']).pickBy().value();

This is not exactly your question, but probably a very common scenario.

var o = { a: 'Not empty', b: null, c: undefined, d: '', e: 100, f: {}, g: [] };

_.pickBy(o, _.isDefined);
// { a: "Not empty", e: 100, f: {…}, g: Array(0) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM