[英]Optional chaining method on find with default value and a ternary operator
i am trying to implement the optional chaining in array.find.我正在尝试在array.find 中实现可选链接。 see the below snippet code i have below three cases
请参阅下面的代码片段我有以下三种情况
But as per the 3 case, if the key value is false its taking the 2 one但是根据第 3 种情况,如果键值为 false,则取 2
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)
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
在访问
.key
之前,您要么需要在 object(这是真实的)上使用它
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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.