首页 > 解决方案 > 如何遍历作为 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>

这是我的问题的截图在此处输入图像描述

先感谢您!

标签: javascriptreactjsecmascript-6

解决方案


您需要遍历数组。

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


推荐阅读