简体   繁体   中英

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:

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

Is there some one-liner using Ramda to do this? I made it using a for loop.

You can use Array.find to find the first item in the array whose key property is truthy , then get the key property.

 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. Things like 0 , '' or false are all non-null values but they are not truthy.

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. find will return the first truthy element from those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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