首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何遍历JSON中键值数组

问如何遍历JSON中键值数组
EN

Stack Overflow用户
提问于 2019-05-30 21:42:41
回答 3查看 81关注 0票数 2

我有这样的JSON文件

代码语言:javascript
复制
[
 {
    "id": 1,
    "country": "Afghanistan",
    "city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
 },
 {
    "id": 2,
    "country": "Italy",
    "city": ["Milano","Rome","Torino","Venezia"]
 }

]

我想迭代放在城市中的数组。我的想法是有两个选择,第一个选择是为国家保留的,第二个选择是为城市保留的。每当用户选择一个国家时,我都想用一个城市列表填充第二个选择。问题是我只收到了那个国家的所有城市的一个数组。下面是我的代码:

​

代码语言:javascript
复制
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>
代码语言:javascript
复制
<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>

​

这是我的问题的屏幕截图

​

提前谢谢你!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-05-30 22:07:21

示例:

代码语言:javascript
复制
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'));
票数 0
EN

Stack Overflow用户

发布于 2019-05-30 21:47:03

您需要遍历数组。

代码语言:javascript
复制
this.state.selectedCountry.city.map((city, index) => {
    return <option value={city} key={index}>{city}</option>
})

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

代码语言:javascript
复制
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

票数 2
EN

Stack Overflow用户

发布于 2019-05-30 21:47:49

您需要在城市数组上使用map()。

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

</select>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56379510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档