API 返回一个对象数组。
我需要从第一个匹配过滤器的对象中提取单个值:
channel = booking.custom_fields.filter(f => f.id == 744)[0].value.trim()
这有效,除非过滤器不匹配任何内容、数组为空或 value==null
。
我知道的唯一方法是:
channel =
booking.custom_fields.filter(f => f.id == 744).length>0 &&
booking.custom_fields.filter(f => f.id == 744)[0].value &&
booking.custom_fields.filter(f => f.id == 744)[0].value.trim()
(如果出现问题,返回 null
或 false
。)
但是这样不够优雅,代码重复很多。
有没有更好的办法?
我唯一能想到的就是try/catch
:
try { channel = booking.custom_fields.filter(f => f.id == 744)[0].value.trim() }
catch { channel = null }
最佳答案
预先使用.find
- 不要试图将它全部压缩到一个语句中。如果找到一个项目,则将值分配给 channel
(否则将 null
分配给 channel
):
const possibleItem = booking.custom_fields.find(f => f.id == 744);
const channel = possibleItem && possibleItem.value ? possibleItem.value.trim() : null;
关于javascript - 检查具有属性的数组对象是否存在的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935415/