简体   繁体   中英

Conditional statement within foreach?

I have a API response that is being used to populate a table. I am assigning links to table items, but would like to provide no link / show the table entry as a blank string IF the response from the API method (getPreauthorizedLink) is a blank string. For example, if element.executiveLink is a blank string, then I would like to not assign a link to this table element and just have it be an empty string.

Here is my code:

  componentDidMount() {
    const _self = this;

    fetch(config.api.urlFor('xxx'))
    .then((response) => response.json())
    .then((data) => {

      const tableContent = [];

      data.array.forEach(element => {
        tableContent.push({
          provider: element.provider,
          type: element.type,
          executiveLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.executiveLink)}}>Report</Link>,
          detailedLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.detailedLink)}}>Report</Link>,
          providerLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.providerLink)}}>Report</Link>
        });

      })

      this.setState({reportJSON: tableContent || [], tableIsBusy: false})

    })
    .catch((err) => _self.setState({tableIsBusy: false }));
  }

Try using shorten if statement:

        tableContent.push({
          provider: element.provider,
          type: element.type,
          executiveLink: element.executiveLink ? <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.executiveLink)}}>Report</Link> : "",
          detailedLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.detailedLink)}}>Report</Link>,
          providerLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.providerLink)}}>Report</Link>
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM