Json object ionization in raect

I have a function in my React app that iterates over the response array from the json api and works fine with the array "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>
        });

      

But how to do the same function, but only for iterating objects. If this.state.person

something like this and I want to read 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}

      

Since the function map

only works on an array and I got the error:

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

      

EDIT (add complete code)

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;

      

it gives me a TypeError due to the map function.

+3


source to share


2 answers


Just store the complete answer in a state value, then refer to a specific property.

let's say that you have saved a full answer in a variable data

and then to access the value lon

, use data.coord.lon

, and if you want loop

the weather, use it like this:

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



Check out this example:

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)
})
      

Run codeHide result


0


source


If you want to map to an arbitrary object, you must use a function Object.keys

. When you call an object, it will give you an array containing keys to all properties of the object. Then you can use map

or forEach

on that array to iterate over it.

For example:



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

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

      

0


source







All Articles