Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through JavaScript object in HTML?

I want to loop through a JavaScript object and repeat an html script as many times as the object length.

Here, I have the following in a script tag

<script>
  var obj;

  ipcRenderer.on('requests-results', (event, hosSchema) => {
    obj = hosSchema
  })
</script>

obj is an array retrieved from Mongo database as the picture below shows:

enter image description here

and I have the following inside <body> tag:

<div class="row">
                <div class="col-md-4 col-sm-4">
                   <div class="card">
                        <div class="card-content">
                          <span class="card-title">.1.</span>
                          <p>.2.</p>
                        </div>
                        <div class="card-action">
                          <a href="#">.3.</a>
                          <a href="#">.4.</a>
                        </div>
                      </div>
                </div>
            </div>

How can I loop through obj to repeat the code between <div> tag as many times as obj.length?

like image 619
mazin Avatar asked Sep 18 '26 07:09

mazin


1 Answers

I would suggest you to use Handlebars as @Amit mentioned.

first move out the code inside <div id="page-inner"> as below:

<div id="page-inner">

</div>

<script id= "requests-template" type="text/x-handlebars-template">
    <div class="row">
        {{#each requests}}
        <div class="col-md-4 col-sm-4">
            <div class="card">
                <div class="card-content">
                    <span class="card-title">{{this.fieldName}}</span>
                    <p>{{this.fieldName}}</p>
                </div>
                <div class="card-action">
                    <a href="#">{{this.fieldName}}</a>
                    <a href="#">{{this.fieldName}}</a>
                </div>
            </div>
            </div>
            {{/each}}
    </div>

</script>

Then inside another script page of type text/javascript you create the requests and assigned obj/hosSchema to it as below:

<script type="text/javascript">
var requestInfo = document.getElementById('requests-template').innerHTML;

        var template = Handlebars.compile(requestInfo);

        var requestData = template({
            requests: obj
        })
        $('#page-inner').html(requestData);
</script>

NOTE: you need handlebars package installed (npm install handlebars --save)

like image 176
Behrouz Riahi Avatar answered Sep 20 '26 20:09

Behrouz Riahi