Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop nested array values using jQuery

Using the following JSON below, how do I loop the inner Errors and Messages values using jQuery:

JSON Format:

{
   "PagesCreated":0,
   "AssetsCreated":0,
   "AssetsUpdated":0,
   "Messages":[
      "Test message!",
      "Test message!",
      "Test message!"
   ],
   "Errors":[
      "Test error!",
      "Test error!",
      "Test error!"
   ],
   "EllapsedTime":"00:00:00.0000382"
}

Current jQuery in place on ajax success call:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$.each(data, function (key, value) {
    if (key == "PagesCreated") {
        console.log(value); // works
    }
    else if (key == "AssetsCreated") {
        console.log(value); // works
    }
    else if (key == "AssetsUpdated") {
        console.log(value); // works
    }
    else if (key == "EllapsedTime") {
        console.log(value); // works
    }
    else if (key == "Messages") {
        // TODO - How do I loop inner Messages values here?
    }
    else if (key == "Errors") {
        // TODO - How do I loop inner Errors values here?
    }
});

If it helps this is the c# object I am serializing to json:

public class MyObj
{
    public int PagesCreated { get; set; }
    public int AssetsCreated { get; set; }
    public int AssetsUpdated { get; set; }
    public TimeSpan EllapsedTime { get; set; }
    public List<string> Messages { get; set; }
    public List<string> Errors { get; set; }
}

Thanks for the help!

>Solution :

You can use .each method again:

$.each(data, function (key, value) {
    if (key == "PagesCreated") {
        console.log(value); // works
    }
    else if (key == "AssetsCreated") {
        console.log(value); // works
    }
    else if (key == "AssetsUpdated") {
        console.log(value); // works
    }
    else if (key == "EllapsedTime") {
        console.log(value); // works
    }
    else if (key == "Messages") {
        $.each(value, function (innerKey, innerValue) {
           console.log(innerValue);
       }
    }
    else if (key == "Errors") {
        $.each(value, function (innerKey, innerValue) {
           console.log(innerValue);
       }
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading