0

I am using React framework.

Here is what I have:

const myObject = this.props.objects.find(({id}) => ({id} === this.state.selectedObject.id));
const name = !isEmpty(myObject) ? myObject.name : '';

I avoid doing the following:

const name = !isEmpty(this.props.objects.find(({id}) => ({id} === this.state.selectedObject.id))) ? this.props.objects.find(({id}) => ({id} === this.state.selectedObject.id)).name : '';

because it doesn't make sense to execute find() twice. But I'm just wondering if there's some nice syntax that can make this a one-liner that I'm missing.

2
  • 2
    really {id} === this.state.selectedObject.id? its never true. Commented May 1, 2020 at 15:11
  • I mean... you could pass the find result as an argument to an IIFE, but that's arguably even less readable that your second formulation: const name = (o=>!isEmpty(o)?o.name:'')(this.props.objects.find(...)) Commented May 1, 2020 at 15:12

2 Answers 2

6

You can use a combination of object destructuring and default parameter like:

const {name = ''} = this.props.objects.find(({id}) => id === this.state.selectedObject.id) || {};

In case find() method, does not find anything then undefined is returned and that will set name to an empty string.

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

3 Comments

You can't destructure undefined, so you'd have to add a || {} at the end.
I like this answer, but Nina's solution imo is slightly easier to read. Any advantage here vs the answer below? Or a matter of preference?
congrats, your answer wins :) there seems to be a bug in babel or webpack that prevents me from using optional operator
3

You could take a optional chaining operator ?. with a default of an empty string.

const
    name = this.props.objects
        .find(({ id }) => id === this.state.selectedObject.id)
        ?.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.