简体   繁体   中英

How to get each field data from arrays passed in object using javascript

{
  "coord": {
    "lon": 73.86,
    "lat": 18.52
  },
  "sys": {
    "message": 0.0083,
    "country": "IN",
    "sunrise": 1436142797,
    "sunset": 1436190324
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 298.644,
    "temp_min": 298.644,
    "temp_max": 298.644,
    "pressure": 948.79,
    "sea_level": 1018.56,
    "grnd_level": 948.79,
    "humidity": 78
  },
  "wind": {
    "speed": 6.46,
    "deg": 253.501
  },
  "clouds": {
    "all": 68
  },
  "rain": {
    "3h": 0.225
  },
  "dt": 1436180142,
  "id": 1259229,
  "name": "Pune",
  "cod": 200
}

This is the data we get after requesting current weather api for information of given city . My question is to make a loop which get all information by looping through data and get all values

I don't want to write like this to get data data.coord.lon data.weather.id etc etc Hope you understand A loop which go in to object and get each array and extract each data/property from array

this is the api for reference http://api.openweathermap.org/data/2.5/weather?q=london have a look

If you mean all the properties for the object received, you could use loop with hasOwnProperty check like here :

for (var key in data) {
    if (obj.hasOwnProperty(key)) {
        //key
        //obj[key] value
    }
}

You can use it recursively to get internal properties in the same way. UPD Here is the fiddle with recursive solution: http://jsfiddle.net/shershen08/xdwqohz1/ :

function listKeys(data){
    for (var key in data) {
        if (data.hasOwnProperty(key)) {

            if((typeof data[key]).toLowerCase() != 'object'){
            console.log(key, data[key])
            } else {
                console.log(key + ': ');
                listKeys(data[key]);
            }
        } 
    }

}

How to list the properties of a JavaScript object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM