用属性检查数组对象是否存在的最佳方法是什么?

时间:2019-05-01 11:18:15

标签: javascript arrays object

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()

(如果出现问题,它将返回nullfalse。)

但这不是很优雅,并且代码重复很多。

有更好的方法吗?

我唯一能想到的是try/catch

try { channel = booking.custom_fields.filter(f => f.id == 744)[0].value.trim() } 
catch { channel = null }

2 个答案:

答案 0 :(得分:4)

请事先使用.find -不要试图将所有内容都压缩成一个语句。如果找到项目,则将值分配给channel(否则将null分配给channel):

const possibleItem = booking.custom_fields.find(f => f.id == 744);
const channel = possibleItem && possibleItem.value ? possibleItem.value.trim() : null;

答案 1 :(得分:0)

我认为这个答案应该是正确的:

const channel = booking.custom_fields.some(e=>e.id==744&&e.value) ? booking.custom_fields.filter(f=>f.id==744)[0].value.trim() : null