javascript - 如何遍历作为 JSON 中键值的数组
问题描述
我有这样的 JSON 文件
[
{
"id": 1,
"country": "Afghanistan",
"city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
},
{
"id": 2,
"country": "Italy",
"city": ["Milano","Rome","Torino","Venezia"]
}
]
我想遍历放置在城市中的数组。想法是有两个选择,其中第一个选择是为国家保留的,第二个是为城市保留的。每当用户选择一个国家时,我想用城市列表填充第二个选择。问题是我只收到该国家所有城市的一个数组。这是我的代码:
export default class DiffCountries extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
contacts: [],
selectedCountry: [],
selectedCity: []
}
}
onChangeHandler = (event) => {
const test = CountriesData[event.target.value - 1];
this.setState({
selectedCountry: test,
selectedCity: this.state.selectedCountry.city
})
console.log(this.state.selectedCity);
}
render() {
const { contacts } = this.state;
return (
<div>
<select name="" id="" onChange={this.onChangeHandler}>
{CountriesData.map(item => {
const { id, country } = item;
return <option key={id} value={id}>{country}</option>
})}
</select>
<select name="" id="">
{this.state.selectedCountry !== undefined ?
<option value="">{this.state.selectedCountry.city}</option> :
null
}
</select>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
先感谢您!
解决方案
您需要遍历数组。
this.state.selectedCountry.city.map((city, index) => {
return <option value={city} key={index}>{city}</option>
})
请注意,使用索引作为键被认为是一种反 模式。您也可以使用城市名称作为键。例如:
this.state.selectedCountry.city.map(city => {
return <option value={city} key={city}>{city}</option>
})
编辑以按照评论中的建议添加指向 mdn 文档的链接:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
推荐阅读
- ckan - 停止/启动ckan docker容器后“未找到数据集”
- ssas - SSAS表格模型:具有相同维度表的两个关系
- redirect - AWS Cognito 电子邮件确认未重定向到我的网站
- git - GIT 将分支代码与最新的修补程序代码合并
- sql - 如何使用 sql select 语句中的列将公式写为列
- python - 熊猫数据框函数返回日期最近的行并且其中一列包含输入值,抛出错误
- angular - Angular 7如何从多个输入上传文件
- spring - 如何使用 @MockBean 和 MockMvc 将一些带有 HTTP POST 的数据附加到模拟存储库
- reactjs - 当父状态更改时,React 子组件不会重新渲染
- android - 添加插件时出错 plugin.google.maps.CordovaGoogleMaps