nested object is undefined using find

Viewed 50
const value = data.find(t => t.user).name;

given above code, my app break if user is null, what's the fallback I could do? I feel this could be duplicated:

data.find(t => t.user) && data.find(t => t.user).name; 
3 Answers

You could simply use the Optional chaining operator. value will then equal undefined and you won't run into an error:

const data = [{}];
const value = data.find(t => t.user === 'someUserId')?.name;
console.log(value);

You could or the value of the find with an empty object.

const data = [{}];
const value = (data.find(t => t.user === 'someUserId') || {}).name;
console.log(value);

Currently, I would use an intermediate step to store the find result.

const found = data.find(t => t.user);
const value = found || found.name;

But it also depends on what you expect value to become if the item is not found in the data array. If you want to fallback to an empty string if it's not found, you could use:

const found = data.find(t => t.user);
const value = found ? found.name : '';
Related