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

looping over nested array to create elements with js/jquery

I come with a problem, I hope you can help me solve.
I have already searched on this side quite a bit, but couldn’t find an answer that solves my problem. I recently worked with looping over objects with jquery each and that worked fine. ATM I need to loop over entries of an array.

This is an example of how the array looks. It contains arrays, which themselves contain the src of an img and the title of the img.

var imgRef = [[http://127.0.0.1:5555/images/imgf0002.png, fig number 1],[http://127.0.0.1:5555/images/imgf0012.png, fig number 12]]

What I would like to do is to loop over the arrays and create a div for each entry. Inside the divs there should be an img containing the src of the other array and a p tag with the name. Then this will be appended to another element on the website.

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

<div>
  <img src="http://127.0.0.1:5555/images/imgf0002.png"> 
  <p>Fig number 1</p>
</div>
<div>
  <img src="http://127.0.0.1:5555/images/imgf0012.png"> 
  <p>Fig number 2</p>
</div>

I have started with this. Just to see whether I can loop over the entries, but it didn’t work.

$.each(imgRef, function (index, value) {
    $('<div />', {
      'text': value
    }).appendTo('#localImg');
  });

>Solution :

you’ve got to iterate over the array with arr.forEach((elem) => {}) or other iterator methods. Since each of elements of the main array, is an array of two elements, you can use array destructuring and use [url, title] instead of elem in the iterator function. Then in the body create the html string from title and url and append it into your target using $.append method.

let theArray = [["url1","title1"],["url2","title2"] /*,...*/];
theArray.forEach(([url, title]) => {
    $('#localImg').append(`<div>
  <img src="${url}"> 
  <p>${title}</p>
</div>`);
});
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