如何遍历作为JSON中键值的数组

时间:2019-05-30 13:42:41

标签: javascript reactjs ecmascript-6

我有这样的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>

这是我的问题enter image description here

的屏幕截图

提前谢谢!

3 个答案:

答案 0 :(得分:2)

您需要遍历数组。

this.state.selectedCountry.city.map((city, index) => {
    return <option value={city} key={index}>{city}</option>
})

请注意,将索引用作键被视为anti pattern。您也可以使用城市名称作为关键字。例如:

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

答案 1 :(得分:2)

您需要在城市阵列上使用map()

<select name = "" id = "" > {
    this.state.selectedCountry !== undefined ?
    this.state.selectedCountry.city.map((x,i) => <option value={x} key={i}>{x}</option>)
    :null
  }

</select>

答案 2 :(得分:0)

示例:

const CountriesData = [
  {
    id: 1,
    country: 'Afghanistan',
    city: ['Eshkashem', 'Fayzabad', 'Jurm', 'Khandud'],
  },
  {
    id: 2,
    country: 'Italy',
    city: ['Milano', 'Rome', 'Torino', 'Venezia'],
  },
];

class DiffCountries extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedCountry: null,
    };
  }

  onChangeHandler = event => {
    const selectedCountry = CountriesData[event.target.value - 1];

    this.setState({
      selectedCountry,
    });
  };

  render() {
    const { selectedCountry } = this.state;
    return (
      <div>
        <select
          name="country"
          defaultValue="country"
          onChange={this.onChangeHandler}
        >
          <option disabled value="country">
            Select country
          </option>
          {CountriesData.map(({ id, country }) => (
            <option key={id} value={id}>
              {country}
            </option>
          ))}
        </select>

        {selectedCountry && (
          <select name="city" defaultValue="city">
            <option disabled value="city">
              Select city
            </option>
            {selectedCountry.city.map(item => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
        )}
      </div>
    );
  }
}

ReactDOM.render(<DiffCountries />, document.getElementById('container'));