1
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 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I know that the optional chaining operator is supported in TypeScript for some time now. But I thought that it is only recently introduced in JavaScript/EcmaScript (version 2020 if I'm not mistaken). So perhaps the OP cannot use it yet. For example if older browsers or IE need to be supported.
That's true, check the compatiblity here -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

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

Comments

0

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 : '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.