使用Ramda的dicts列表中的第一个非null值



让我们假设我想获得这个对象列表中不为null的键的第一个值:

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

有没有一个班轮使用拉姆达来做这件事?我用for循环做的。

您要求第一个非空键,但到目前为止,答案取决于真实性。在JavaScript中,非null值不一定是真的。像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}

使用Ramda:

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

prop函数将为每个元素返回key的值。CCD_ 6将返回这些元素中的第一个CCD_。

您可以使用Array.find查找数组中key属性为true的第一个项,然后获取key属性。

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

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

最新更新