如何在javascript中将变量用作json数组中的键

时间:2013-12-26 06:05:24

标签: javascript json

我跟随json formate

"[{"tempId":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"

在上面的格式中 tempId不是字符串值,它是变量。它的值类似于"25Dec2013"。但是它被插入,因为它意味着一个名字变量而不是值。

所以看起来应该是

"[{"tempId":[{"25Dec2013":"London"},{"weather":"overcast clouds"}]}]"

我已经完成了以下代码。我在代码中写了一条评论,实际问题是

var arrCityrecordForADay = [];

function getWeatherDataForCities(cityArray,callback){

var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24 * 60 * 60);
for (var i in cityArray) {

    for (var j = 1; j <= 2; j++) {
        var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q=" + cityArray[i] + "&dt=" + toDaysTimestamp;

        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                var arrCityRecordForDay = [];
                arrCityRecordForDay.push({
                    "cityName": data.list[0].city.name
                }, {
                    "weather": data.list[0].weather[0].description
                });

                var tempId = data.list[0].city.name+""+timeConverter(data.list[0].dt);
                arrCityrecordForADay.push({
                    tempId: arrCityRecordForDay // Here tempId is inserted as "tempId" not its value
                });

                if (((arrCityrecordForADay.length)) === cityArray.length) {
                    callback(arrCityrecordForADay);
                }

            }
        });
        toDaysTimestamp = toDaysTimestamp - (24 * 60 * 60);
    }
}
}

$(document).ready(function () {
  var cityArray = new Array();
  cityArray[0] = "pune";
  cityArray[1] = "london";
  var result = document.getElementById("msg");
  getWeatherDataForCities(cityArray, function (jsonData) {
  var myJsonString = JSON.stringify(jsonData);
      console.log(myJsonString);
  });
});

function timeConverter(UNIX_timestamp){

 var a = new Date(UNIX_timestamp*1000);

 var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

 var year = a.getFullYear();

 var month = months[a.getMonth()];
 var date = a.getDate();
 var hour = a.getHours();
 var min = a.getMinutes();
 var sec = a.getSeconds();
 //var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
 var time = date+''+month+''+year;
 return time;
}

如何在上面的示例中将变量作为键插入?

修改

为什么输出不稳定。有时候错了,有时候是正确的。 这是正确的输出:

"[{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"London22Dec2013":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"

有些时候它会在刷新后显示以下输出。

"[{"Pune24Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]}]"

如何克服这个问题?

您的回复将受到关注!!

1 个答案:

答案 0 :(得分:3)

您必须使用临时变量来实现此目的:

var obj = {};
obj[tempId] = arrCityRecordForDay;
arrCityrecordForADay.push(obj);