9

Yes there are many post regarding this.But my doubt is little different.I have following array for example

var dictionary = {
    "12Jan2013": [{
        "id": "0",
        "name": "ABC"
    }, {
        "id": "1",
        "name": "DEF"
    }],
    "13Jan2013": [{
        "id": "0",
        "name": "PQR"
    }, {
        "id": "1",
        "name": "xyz"
    }]
};

Same post is there on same site BUT here in dictionary json array key is dynamic.Here it is date ie 12Jan2013.It can be any date.It is not static.I have searched for that but didn't get solution.

How to iterate over such a json array?

AND How to print json array as in same formate shown above?

EDIT

Here is my real code.And i shown a comment in following code where i wanted to iterate data ie jsonData var in getWeatherDataForCities callback

var arrAllrecords = [];
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<=1; 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 = [];
                /*arrCityrecordForADay.push(data.list[0].city.name);
                arrCityrecordForADay.push(data.list[0].weather[0].description);
                arrCityrecordForADay.push(timeConverter(data.list[0].dt));
                arrCityrecordForADay.push(data.list[0].main.temp);
                arrCityrecordForADay.push(data.list[0].main.humidity);
                arrCityrecordForADay.push(data.list[0].main.pressure)
                arrCityrecordForADay.push(data.list[0].wind.speed);*/
                //'{"pets":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';

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

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

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

$(document ).ready(function() {

 var cityArray = new Array();
  cityArray[0] = "pune";

  getWeatherDataForCities(cityArray, function(jsonData) {
        // Here I want to iterate jsonData
  });


});
Majid
  • 13,853
  • 15
  • 77
  • 113
Prashant Shilimkar
  • 8,402
  • 13
  • 54
  • 89

4 Answers4

10

Use for-in...something like:

for (var i in dictionary) {
    dictionary[i].forEach(function(elem, index) {
        console.log(elem, index);
    });
}

where the i would iterate through your dictionary object, and then you can use forEach for every json array in the dictionary(using dictionary[i])

With this code you'll get

Object {id: "0", name: "ABC"} 0 
Object {id: "1", name: "DEF"} 1 
Object {id: "0", name: "PQR"} 0 
Object {id: "1", name: "xyz"} 1 

You can tailor the forEach function definition(replacing the console.log bit) to do whatever you want with it.

DEMO

Edit: Doing the same thing using Object.keys

Object.keys(dictionary).forEach(function(key) {
    dictionary[key].forEach(function(elem, index) {
        console.log(elem, index);
    });
});

Edit2: Given the somewhat complicated structure of your jsonData object, you could try using a (sort of) all-purpose function that would act on each type of component separately. I've probably missed a few cases, but maybe something like:

function strung(arg) {
    var ret = '';
    if (arg instanceof Array) {
        arg.forEach(function(elem, index) {
            ret += strung(elem) + ',';
        });
    } else if (arg instanceof Object) {
        Object.keys(arg).forEach(function(key) {
            ret += key + ': /' + strung(arg[key]) + '/';
        });
    } else if (typeof arg === "string" || typeof arg === "number") {
        ret = arg;
    }
    return ret;
}

document.body.innerHTML = strung(jsonData);

DEMO

tewathia
  • 6,890
  • 3
  • 22
  • 27
  • 1
    If you're using `forEach` you might as well use `Object.keys` and have pretty code all the way :) – Benjamin Gruenbaum Dec 25 '13 at 13:54
  • Also note that you will also want to use `hasOwnProperty(i)` to filter out properties that may have been inherited. – Ryan Ransford Dec 25 '13 at 13:55
  • @RyanRansford Just wondering, how would that be relevant in this case? – Benjamin Gruenbaum Dec 25 '13 at 13:56
  • 1
    @BenjaminGruenbaum I'm not as comfortable with `Object.keys` as I'd like to be...I've added an edit to my answer. Is that what you meant? – tewathia Dec 25 '13 at 14:03
  • @PrashantShilimkar Let me make a fiddle – tewathia Dec 25 '13 at 14:04
  • @tewathia It will be gr8 for me to understand.And let me update question what i actually did to create that(not same value) array. – Prashant Shilimkar Dec 25 '13 at 14:06
  • 1
    @PrashantShilimkar I've added the fiddle link to my answer. Have a look – tewathia Dec 25 '13 at 14:09
  • @tewathia your answer is perfect.but i have made some mistack in my code posted in edited answer thats why it is not showing out put.Will you please tell whats going wrong. – Prashant Shilimkar Dec 25 '13 at 14:18
  • 1
    @PrashantShilimkar At a glance, your code looks okay to me(I'm assuming `timeConverter` is defined elsewhere). Let me add though, you can't use my answer directly with your `jsonData` object, because its structure is slightly different. See this [fiddle](http://jsfiddle.net/tewathia/TTuFS/) – tewathia Dec 25 '13 at 14:34
  • @BenjaminGruenbaum Doesn't the instantiated object inherit some properties from Object, or is `{}` treated slightly differently than `new Object()`? – Ryan Ransford Dec 27 '13 at 13:56
1

Please note that yours is just a JavaScript array object. To make it simple to understand, you can iterate over it like this:

for (var i in dictionary) {
    // do something with i
    // here i will contain the dates

    for (n = 0; n < dictionary[i].length; n++) {
        // do something with the inner array of your objects    
        // dictionary[i][n].id contains the "id" of nth object in the object i
        // dictionary[i][n].name contains the "name" of nth object in the object i
    }
}

See this fiddle: http://jsfiddle.net/Ke8F5/

The iteration looks like this:

12Jan2013 : (id = 0, name = ABC) (id = 1, name = DEF)  
13Jan2013 : (id = 0, name = PQR) (id = 1, name = XYZ)
Abhitalks
  • 27,721
  • 5
  • 58
  • 81
  • Thank you.I have edited my question where i have created a dynamic json array.Is it the right way or what i have did is correct? – Prashant Shilimkar Dec 25 '13 at 14:13
  • @PrashantShilimkar: It all depends on how `data` is structured in your ajax call. Nevertheless, the concept remains the same. – Abhitalks Dec 25 '13 at 14:15
0

You can use a for loop.

for (var i in json) {
 ...
}

Then, i is the current key, so, you can acess json[ i ] and get the data to the corresponding index.

And then, if you need to iterate over inner elements, you can do the same thing.

Andrey
  • 1,476
  • 1
  • 11
  • 17
0

You can use for ... in but you should combine it with hasOwnProperty or you'll find yourself iterating over inherited properties likely breaking your code.

  for (var key in object) {
    if (object.hasOwnProperty(key)) {
        // Do stuff.
    }
  }
Jonathan
  • 8,771
  • 4
  • 41
  • 78