简体   繁体   中英

Looping through json object that has an array with javascript

What I'm trying to output with JS :

<ul>
  <li>title1
    <ul>
      <li>image1</li>
      <li>image2</li>
      <li>image3</li>
   </ul>
  </li>
  <li>title2
    <ul>
      <li>image1</li>
      <li>image2</li>
      <li>image3</li>
   </ul>
  </li>

...and so forth...

</ul>

JSON:

var data = [
    {
        title: "title1", 
        image:["image1", "image2", "image3"]
    },
    {
        title: "title2", 
        image:["image1", "image2", "image3"]
    },
    {
        title: "title3", 
        image:["image1", "image2", "image3"]
    },
    {
        title: "title4", 
        image:["image1", "image2", "image3"]
    }
];

My JS

for(var i=0; i < data.length; i++) {
  var item = data[i];
  var obj = {
      title:item.title,
      image:item.image
  };
  var theimages;
  var html = '';

    for(j=0; j < item.image.length; j++) {
         theimages = '<li>' + item.image[j] + '</li>'; 
    }

html += '<li>' + item.title + '<ul>';
html += theimages;
html += '</ul></li>';
} 
console.log(html);

Can someone explain how do I get the value of the inner for loop and combine it with the outer for loop so that I end up with output I'm trying to achieve. currently I end up with this:

<li>title4
  <ul>
    <li>image3</li>
  </ul>
</li>

You just need to append it to the string, instead of reassigning the variable again and again:

var theimages;
var html = '<ul>';
for(var i=0; i < data.length; i++) {
  var item = data[i];
  var obj = {
      title:item.title,
      image:item.image
  };


for(j=0; j < item.image.length; j++) {
         theimages += '<li>' + item.image[j] + '</li>'; 
    }

html += '<li>' + item.title + '<ul>';
html += theimages;
html += '</ul></li>';
}  
html += '</ul>';
console.log(html);

the problem is that you overwrite the html variable in every iteration of the outer for-loop.

If you declare this variable before the loop, you get the right result. Also you don't want to overwrite the theimages variable everytimes, but append the new portion to it.

var html = '';
for(var i=0; i < data.length; i++) {
  var item = data[i];
  var theimages = '';
  for(j=0; j < item.image.length; j++) {
    theimages += '<li>' + item.image[j] + '</li>'; 
  }

  html += '<li>' + item.title + '<ul>';
  html += theimages;
  html += '</ul></li>';
} 
console.log(html);

Also I have removed your obj-variable, since you did not use it anyway.

Just use this pattern, if you build strings: var myString = '' for(item ...) { myString += item } At first initialize the string, then append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM