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

Javascript – Looping an object inside an loop

Not sure if I am phrasing this exactly but I have an object that I want to create a variable from to then append to a div in a page. I am doing this in javascript / Jquery.

The object:

   var object = [
      {
        "explanation": [
          "Test 1",
          "Test 2",
          "Test 3",
        ],
        "issue": "Walking, Biking, and Transit"
      },
      {
        "explanation": [
          "Test 1",
          "Test 2",
        ],
        "issue": "Affordable Housing"
      },
      {
        "explanation": [
          "Test 3"
        ],
        "issue": "Placemaking"
      }

Then I loop it to get the data but want to create a var of html to then append but need to loop the explanation.

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(object, function (key, val) {

      var title = val.issue;
      var items = val.explanation;

      console.log(title, items);

      var item =
        '<div class="flex items-center justify-between w-full p-2 mt-2 bg-gray-200 rounded-lg"> ' +
        '  <div>' + title + '</div> ' +
        //LOOP items here to create a list of sub items for the parent.
        '  <div>' + items + '</div> ' +
        '</div> ';

      $("#gridArea").append(item);

    });

I cannot figure out how to loop the multiple explanations inside each object item to create this div, append, repeat.

If there is a better way let me know! I keep thinking to PHP where I can split it up from to create HTML loop HTML loop, etc. but don’t have experience with that here.

>Solution :

for(let obj of object){
    let issue = obj.issue;
    for(let exp of obj.explanation){
        console.log(exp)
    }
}
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