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

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

假设我想获取此对象列表中非空的第一个键值:

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

有没有使用 Ramda 的单行代码?我使用 for 循环实现了它。

您可以使用Array.find to find the first item in the array whose key property is truthy,然后得到key 属性。

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


const res = arr.find(e => e.key).key;

console.log(res)

使用 Ramda:

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

prop函数将为每个元素return取key的值。 find 将 return 第一个 truthy 元素。

您要求提供第一个非空密钥,但到目前为止的答案取决于真实性。在 JavaScript 中,非空值不一定为真。 0''false 之类的东西都是非空值,但它们不是真实的。

根据我的经验,最好是明确的,否则你可能会得到意想不到的结果:

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}