Reputation: 1389
An API returns an array of objects.
I need to extract a single value from the first object which matches a filter:
channel = booking.custom_fields.filter(f => f.id == 744)[0].value.trim()
This works, except when the filter matches nothing, the array is empty, or value==null
.
The only way I know around this is:
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()
(which returns null
or false
if there was a problem.)
But this is not elegant and a lot of repetition of code.
Is there a better way?
The only thing I can think of is try/catch
:
try { channel = booking.custom_fields.filter(f => f.id == 744)[0].value.trim() }
catch { channel = null }
Upvotes: 1
Views: 41
Reputation: 22265
I think this one should be a correct answer :
const channel = booking.custom_fields.some(e=>e.id==744&&e.value) ? booking.custom_fields.filter(f=>f.id==744)[0].value.trim() : null
Upvotes: 0
Reputation: 370699
Use .find
beforehand - don't try to squash it all into one statement. If an item is found, assign the value to channel
(else assign null
to channel
):
const possibleItem = booking.custom_fields.find(f => f.id == 744);
const channel = possibleItem && possibleItem.value ? possibleItem.value.trim() : null;
Upvotes: 4