我正在编写一个ReactJS应用程序,并且在函数filterSelected中有一个for循环,该函数遍历区域名称(例如["Thailand", "Malaysia"])的数组,并且应该返回其对应的区域代码(例如["TH", "MY"] )。

在我的mapRegionToCode函数中,它通过对象的对象进行映射,并且控制台日志正确打印​​了相应的区域代码,但是该函数返回了undefined

任何想法,为什么将不胜感激!

mapRegionToCode(region) { // region = "Thailand"
  _.forEach(_.values(this.props.regionsCodes), regionCode => {
    if(regionCode.country.countryName === region) {
      console.log(regionCode.country.countryCode); //"TH"
      return regionCode.country.countryCode;
    }
  });
}

filterSelected(filters) {
...
  for(let i = 0; i < regionsArray.length; i++){
    const regionCode = this.mapRegionToCode(regionName);
    console.log(regionCode); //undefined
    regionNames.push(regionCode);
  }
...
}

最佳答案

更新资料

我读了你想做错的事。您需要执行以下操作:


country.countryName === region查找regionCode
返回其country.countryCode


使用lodash,您可以执行以下操作:

mapRegionToCode(region) {
  return _.find(_.values(this.props.regionsCodes),regionCode => regionCode.country.countryName === region).country.countryCode
}


原始答案

您忘记在return函数中添加mapRegionToCode了:

mapRegionToCode(region) { // region = "Thailand"
  return _.map(_.values(this.props.regionsCodes), regionCode => {
    if(regionCode.country.countryName === region) {
      console.log(regionCode.country.countryCode); //"TH"
      return regionCode.country.countryCode;
    }
  });
}


(此外,您需要使用_.map而不是_.forEach

10-05 20:44
查看更多