-1
{
  "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

1 Answers1

2

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

Community
  • 1
  • 1
shershen
  • 9,875
  • 11
  • 39
  • 60
  • var city = $('#city').val(); $.get("http://api.openweathermap.org/data/2.5/weather?q=" + city, function (data, status) { console.log(status); $.each(data, function (index,value) { console.log(index + ": " + value); //for (var i = 0 ; i < index.length; i++) { // console.log(index[1]); //} }); },"JSON"); – Narendra Singh Rathore Jul 06 '15 at 12:28
  • and getting this success (index):44 coord: [object Object] (index):44 sys: [object Object] (index):44 weather: [object Object] (index):44 base: stations (index):44 main: [object Object] (index):44 wind: [object Object] (index):44 clouds: [object Object] (index):44 rain: [object Object] (index):44 dt: 1436184609 (index):44 id: 1259229 (index):44 name: Pune (index):44 cod: 200 – Narendra Singh Rathore Jul 06 '15 at 12:28
  • so what is your question? this comment with code is hard to read actually – shershen Jul 07 '15 at 08:18