开发者问题收集

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

2013-12-26
1248

我有以下 json 格式

"[{"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个回答

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

var obj = {};
obj[tempId] = arrCityRecordForDay;
arrCityrecordForADay.push(obj);
xdazz
2013-12-26