简体   繁体   English

使用 lodash 从对象中选取定义的值

[英]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 :我想挑出_idstatuscurrent_task属性,但current_task是它们不是nullundefined

{
  _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?是否有一个 lodash 函数可以做我想做的事?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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