让我们假设我想获得这个对象列表中不为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)