JS / JQuery在多维对象中获取键的值

时间:2015-10-01 21:46:33

标签: javascript jquery arrays object multidimensional-array

我觉得让我恢复能力的一件事就是了解如何有效地使用数组和对象。我得到了基础知识,但是当涉及到在复杂对象中需要特定键和值时,我会迷失方向。所以在这个例子中,我从 openweathermap 获取一个对象。该对象如下所示:

{
    "coord":{
        "lon":-83.15,
        "lat":41.51
    },
    "weather":[
        {
            "id":721,
            "main":"Haze",
            "description":"haze",
            "icon":"50d"
        }
    ],
    "base":"cmc stations",
    "main":{
        "temp":287.05,
        "pressure":1024,
        "humidity":47,
        "temp_min":286.15,
        "temp_max":288.15
    },
    "wind":{
        "speed":5.1,
        "deg":50,
        "gust":9.3
    },
    "clouds":{
        "all":40
    },
    "dt":1443728852,
    "sys":{
        "type":1,
        "id":1435,
        "message":0.0115,
        "country":"US",
        "sunrise":1443699000,
        "sunset":1443741203
    },
    "id":5165215,
    "name":"Oak Harbor",
    "cod":200
}

我了解如何使用 each()

遍历数组
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
    $.each(obj.main, function(key, val) {
        //do something//
    });
});

但是如果我想访问对象中更深层次的内容,比如说我特别想要温度值例如,然后将其分配给全局变量以在脚本之外使用。我想较少需要一个特定的解决方案,但更多关于如何使用像这样的复杂对象的一个​​很好的解释。

感谢您的帮助!

所以我现在有了这个,但是这个值没有被传递出来?

$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
    currentTemp = (obj.main.temp * 9/5 - 459.67);
    alert(currentTemp);
});

alert(currentTemp);

2 个答案:

答案 0 :(得分:0)

$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
    $.each(obj.main, function(key, val) {
        if(val.temp)
        {
            // do what you want with the temperature
        }
    });
});

答案 1 :(得分:0)

你可以这样:

$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
    $.each(obj, function(key, val) {
        your_global_var = val.main.temp;
    });
});

或者如果您想获得更多信息。

$.each

无论如何,我认为不需要$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) { your_global_var = obj.main.temp; }); 循环,因为你可以这样:

xmlEventParse
相关问题