如何以编程方式解决某些问题

时间:2015-06-26 15:15:14

标签: javascript jquery

我有以下代码:

$LimitLoop = 50;
$i = 0;
foreach ($customers as $customer) {
    if ($i++ >= $LimitLoop) {
        break;
    }
    // the rest of the loop
}

数据输出为:

;(function($){

    var getWeatherInfo = function(url, requiredKeys ) {

        var info = {},
            dfd = $.Deferred();

        $.getJSON( url, function( data ) {  
            for(var i = 0; i < requiredKeys.length; i++) {
                info[requiredKeys[i]] = data[requiredKeys[i]];
            }

            dfd.resolve(info);
        }); 

        return dfd.promise();
    };  

 var url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
    requiredData = [
                    'name',
                    'coord.lat',
                    'coord.lon',
                    'description'
                  ]; 
 getWeatherInfo(url,requiredData).done(function(data){console.log(data)});

Object {name: "London", coord.lat: undefined, coord.lon: undefined, description: undefined} 工作正常,因为它没有Name我该如何解决休息问题?我不想使用eval。还有更好的选择吗?

1 个答案:

答案 0 :(得分:1)

这将有效:

$.getJSON( url, function( data ) {  
            for(var i = 0; i < requiredKeys.length; i++) {
                if (requiredKeys[i].indexOf('.') > -1){
                    var ar = requiredKeys[i].split("\.");
                    info[requiredKeys[i]] = data[ar[0]][ar[1]]
                }
                else{
                    info[requiredKeys[i]] = data[requiredKeys[i]];
                }
            }

            dfd.resolve(info);
        }); 

结果:对象{name:&#34; London&#34;,coord.lat:51.51,coord.lon:-0.13,description:undefined}

http://jsfiddle.net/gpzd9w43/

编辑:

如果您有超过1个点,也许可以采用更优雅的方式:

    $.getJSON( url, function( data ) {  
        for(var i = 0; i < requiredKeys.length; i++) {
            var ar = requiredKeys[i].split("\.");
            var node = data;

            for (var j = 0; j < ar.length; j++){
                node = node[ar[j]];
            }

            info[requiredKeys[i]] = node;
        }

        dfd.resolve(info);
    }); 

http://jsfiddle.net/gpzd9w43/1/