简体   繁体   中英

Check substring in array javascript

when I have the word SAC and Assessoria inside the array it just returns the first if, what is wrong with this logic?

If the array (skills) has the substring SAC I want to make a setState with response.data.SAC which is also an array

If the array (skills) has the substring Assessoria I want to make a setState with response.data.AC which is also an array

if you have both substrings SAC and Assessoria, I want to make a setState with response.data.SAC and response.data.AC, they are both arrays

code below:

getDataTab() {
    const URL = `${Utils.ngrok_service}`;

    const skills = this.props.manager.workerClient.attributes.routing.skills;

    axios.post(URL).then((response) => {

      skills.map((item, index) => {

        if (item.includes('SAC')) {
          console.log('SAC EXISTE');
          this.setState({ options: response.data.SAC });
        } else if (item.includes('Assessoria')) {
          console.log('AC EXISTE');
          this.setState({ options: response.data.AC });
        } else if (item.includes('SAC') && item.includes('Assessoria')) {
          console.log('ambos EXISTE');
          this.setState({
            options: [...response.data.SAC, ...response.data.AC],
          });
        } else {
          console.log('nada EXISTE');
        }
      });
    });
  }

You are setting the state once on each iteration, instead of iterating over the whole array first to check the conditions. The order of your conditional checks is also incorrect.

let hasSAC = false, hasAssessoria = false;
skills.forEach(item=>{
    hasSAC = hasSAC || item.includes("SAC");
    hasAssessoria = hasAssessoria || item.includes("Assessoria");
});
if(hasSAC && hasAssessoria){
     console.log('ambos EXISTE');
     this.setState({
        options: [...response.data.SAC, ...response.data.AC],
     });
} else if(hasSAC){
     console.log('SAC EXISTE');
     this.setState({ options: response.data.SAC });
} else if(hasAssessoria){
    console.log('AC EXISTE');
    this.setState({ options: response.data.AC });
} else {
    console.log('nada EXISTE');
}

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