d0g
d0g

Reputation: 1389

What is the best way to check for existence of array object with property?

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

Answers (2)

Mister Jojo
Mister Jojo

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

CertainPerformance
CertainPerformance

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

Related Questions