Prashant Shilimkar
Prashant Shilimkar

Reputation: 8820

How to use a variable as key in json array in javascript

I have following json formate

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

In above format tempId is not a String-value it is a variable.It's value is something like "25Dec2013".But it is inserted as it is mean a name of variable and not a value.

So it should look like

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

I have done following code.I have written one comment in code where the actual problem is.

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;
}

How to insert a variable as a key in above example?

EDIT:

And Why output is not stable.Some time wrong and sometime correct. Here is correct output:

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

Some times it shows following output after some refresh.

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

How to overcome this?

Your response will be appriciated !!

Upvotes: 1

Views: 1268

Answers (1)

xdazz
xdazz

Reputation: 160833

You have to use a temp variable to achieve this:

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

Upvotes: 3

Related Questions