我正在编写一个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
)