Optional chaining method on find with default value and a ternary operator

Viewed 918

i am trying to implement the optional chaining in array.find. see the below snippet code i have below three cases

  1. if array is empty i need to have the true // by default true
  2. if the array didn't find the object it should also be true // empty as true value
  3. if the array has the object it should take the key property value // true or false

But as per the 3 case, if the key value is false its taking the 2 one

let array = [{
  id: 1,
  key: false
}, {
  id: 2,
  key: true
}]
let key =
  array && array.length ?
  array.find(
    (item) => item.id === 1
  )?.key || "empty as true value" :
  "by default true";
  
 console.log(key)

1 Answers

You cannot use || when the left-hand side value can be falsy. You will either need to use it on the object (which is truthy) before accessing the .key

const key = (array?.find(item =>
  item.id === 1
) || {key: "empty as true value"}).key;

or better use the nullish coalescing operator:

const key = array?.find(item =>
  item.id === 1
)?.key ?? "empty as true value";
Related