Search code examples
javascriptjqueryjsonhandlebars.jstemplating

Looping through an array of json objects


So, I have this web app in which I am using hbs as the templating engine. Now, from my rest API I am sending over an array of JSON objects:

 [{";_id":"5704630a7d4cd367f8dsdce7","name":"Seagate","description":"This awesome Hard disk" ,"categories":["SDD","256GB"]}]

I have a variable: disklist, that has this data.

Using handlebars this is what I have tried so far, but it does not seem to work.

  console.log(disklist[0].name); // LOGS THE NAME PROPERLY

  var source   = $("#dlist").html();
  var template = Handlebars.compile(source);
  var wrapper  = {objects: disklist};

In html:

<script type='text/template' id='dlist'>
  <li>
   {{#each objects}}
        <h1>{{name}}</h1>
   {{/each}}
  </li>
</script>

But nothing prints!

How do I fix this?

Also, if there is a way to do this with just bare-bones JavaScript, please do share!


Solution

  • Plain js:

    var disklist = [
        {";_id":"5704630a7d4cd367f8dsdce7","name":"Seagate","description":"This awesome Hard disk" ,"categories":["SDD","256GB"]},
        {";_id":"5704630a7d4cd367f8dsdce7","name":"Seagate2","description":"This awesome Hard disk" ,"categories":["SDD","256GB"]},
        {";_id":"5704630a7d4cd367f8dsdce7","name":"Seagate3","description":"This awesome Hard disk" ,"categories":["SDD","256GB"]}
    ];
    
    
    document.getElementById('container').innerHTML = disklist.map(function(disk) {
      return '<li><h1>' + disk.name + '</h1></li>';
    }).join('');
    <ul id="container">
    </ul>

    Not sure if this is what you want ?

    WALKTHROUGH: We create an element and make it the container of what we are going to render into. Next we set it's innerHTML to a string which is what we are going to create. disklist.map go through the disklist array and apply each item with a string, which is <li><h1>{{disk.name}}</h1></li> in this case. You can change the content to whatever you like, it's just HTML. Then, we join the array of strings into one big string using .join(''). Finally, we set the innerHTML to the string we just created, dala.