简体   繁体   English

使用 Ramda 的字典列表中的第一个非空值

[英]First non-null value from a list of dicts using Ramda

Let's suppose that I want to get the first value of key that is not null inside this list of objects:假设我想在这个对象列表中获取不是 null 的键的第一个值:

const arr = [
    {
      "key": null,
      "anotherkey": 0
    },
    {
      "another": "ignore"
    },
    {
      "bool": True,
      "key": "this!"
    }
  ]

Is there some one-liner using Ramda to do this?是否有一些单线使用 Ramda 来做到这一点? I made it using a for loop.我使用 for 循环实现了它。

You can use Array.find to find the first item in the array whose key property is truthy , then get the key property.您可以使用Array.find查找数组中key属性为真值的第一项,然后获取key属性。

 const arr = [{ "key": null, "anotherkey": 0 }, { "another": "ignore" }, { "bool": true, "key": "this." } ] const res = arr.find(e => e.key);key. console.log(res)

You asked for the first non-null key but answers so far rely on truthyness.您要求第一个非空键,但到目前为止的答案依赖于真实性。 In JavaScript a non-null value is not necessarily truthy.在 JavaScript 中,非空值不一定是真的。 Things like 0 , '' or false are all non-null values but they are not truthy.诸如0''false之类的东西都是非空值,但它们不是真实的。

In my experience it is better to be explicit otherwise you may get unexpected results:根据我的经验,最好是明确的,否则您可能会得到意想不到的结果:

var data = [{key:null, val:1}, {key:0, val:2}, {key:1, val:3}];

find(prop('key'))(data);
//=> {key:1, val:3}

find(propSatisfies(complement(isNil), 'key'))(data);
//=> {key:0, val:2}

With Ramda:与拉姆达:

R.find(R.prop("key"))(arr);

prop function will return the value of key for each element. prop function 将返回每个元素的key find will return the first truthy element from those. find将从这些元素中返回第一个truthy元素。

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

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