[英]First non-null value from a list of dicts using Ramda
假設我想在這個對象列表中獲取不是 null 的鍵的第一個值:
const arr = [
{
"key": null,
"anotherkey": 0
},
{
"another": "ignore"
},
{
"bool": True,
"key": "this!"
}
]
是否有一些單線使用 Ramda 來做到這一點? 我使用 for 循環實現了它。
您可以使用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)
您要求第一個非空鍵,但到目前為止的答案依賴於真實性。 在 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}
與拉姆達:
R.find(R.prop("key"))(arr);
prop
function 將返回每個元素的key
。 find
將從這些元素中返回第一個truthy
元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.