簡體   English   中英

使用lodash forEach返回未定義的Javascript函數

[英]Javascript function using lodash forEach returning undefined

我正在編寫一個ReactJS應用程序,並且在filterSelected函數中有一個for循環,該函數filterSelected了區域名稱的數組(例如["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);
  }
...
}

更新資料

我讀了你想做錯的事。 您需要執行以下操作:

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

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

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

原始答案

您忘記在mapRegionToCode函數中添加return

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM