反应中的JSON对象迭代

时间:2017-04-04 15:59:33

标签: javascript reactjs ecmascript-6

我的React应用程序中有一个函数,它从JSON API迭代响应数组,它可以与数组"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}]一起使用:

render() {
    const persons = this.state.person.map((item) => {
       return <div>
       <h1>{item['id']}</h1>
       <span>{item['name']}</span>
       </div>
    }
}

但是如何创建相同的函数但仅用于对象迭代?如果this.state.person是这样的,我想阅读coord['lon']

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}

由于map函数仅适用于数组,因此出现此错误:

this.state.person.map is not a function TypeError

编辑(添加完整代码)

class App extends React.Component {
  constructor(props){
    super();
    this.state = {
      person: [],
        cityName: 'London'
    };
  }

    componentDidMount() {
        this.UserList();
    }

    update(e){
      this.setState({cityName: e.target.value})
    }

  UserList(city = this.state.cityName){
      let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=c24bda9c5812d6be82860b70c35d41a5';
    return $.getJSON(weatherURL).then((response) => {this.setState({person: response.coord})});
  }

    render() {
        const persons = this.state.person.map((item) => { // it gives me TypeError,
            return <div>
              <h1>{item[0]}</h1>
              <span>{item[1]}</span>
            </div>
        });

        return <div id="layout-content" className="layout-content-wrapper">
          <input type="text"
          onChange={this.update.bind(this)}/>
          <div className="panel-list">{ persons }</div>
        </div>
    }
}

export default App;

由于地图功能,它会返回TypeError

2 个答案:

答案 0 :(得分:0)

只需将完整响应存储在状态值中,然后访问特定属性。

假设您在变量data中存储完整的回复,然后使用lon访问data.coord.lon值,如果您希望loop超过天气,请使用它这样:

data.weather.map(item => console.log(item.main))

检查此示例:

&#13;
&#13;
let data = {
	"coord":{
		"lon":-0.13,
		"lat":51.51
	},
	"weather":[
		{
			"id":300,
			"main":"Drizzle",
			"description":"light intensity drizzle",
			"icon":"09d"
		}
	],
	"base":"stations",
	"main":{
		"temp":280.32,
		"pressure":1012,
		"humidity":81,
		"temp_min":279.15,
		"temp_max":281.15
	},
	"visibility":10000,
	"wind":{
		"speed":4.1,
		"deg":80
	},
	"clouds":{
		"all":90
	},
	"dt":1485789600,
	"sys":{
		"type":1,
		"id":5091,
		"message":0.0103,
		"country":"GB",
		"sunrise":1485762037,
		"sunset":1485794875
	},
	"id":2643743,
	"name":"London",
	"cod":200
}

console.log('coord', data.coord.lon);

data.weather.map(item=>{
	console.log(item.main)
})
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果要映射任意对象,则应使用Object.keys函数。在对象上调用时,它将为您提供一个包含所有对象属性的键的数组。然后,您可以在此数组上使用mapforEach来迭代它。

例如:

const person = this.state.person
const personKeys = Object.keys(person)

personKeys.map(key => do_something_with(key))