How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this:

{
"network": 
   [
    { "name": [ "John",   "Jill",  "June"  ] },
    { "town": [ "London", "Paris", "Tokyo" ] },
    { "age" : [ "35",     "24",    "14"    ] }
   ]
}

Unfortunately, my data is in this format and I have to work with it.

I am aiming for an HTML output as below:

<ul>
<li>John, London, is 35 years old.</li>
<li>Jill, Paris, is 24 years old.</li>
<li>June, Tokyo, is 14 years old.</li>
</ul>

(In essence, iterating through the JSON by index - 0, then 1, then 2 :

<ul>
<li>{{name}}[0], {{town}}[0], is {{age}}[0] years old.</li>
<li>{{name}}[1], {{town}}[1], is {{age}}[1] years old.</li>
<li>{{name}}[2], {{town}}[2], is {{age}}[2] years old.</li>
</ul>

)

Is there a built-in method, using handlebarsJS, to create a template like this:

  {{#each network}}<li>{{name}}[i], {{town}}[i], is {{age}}[i] years old.</li>{{/each}}

?

Answer №1

@Hugolpz, before you start using your template, it's important to reorganize your data. Templates should only focus on generating output and not contain any decision-making logic.

<script>
    var original = { "network":[
        { "name": [ "John",   "Jill",  "June"  ] },
        { "town": [ "London", "Paris", "Tokyo" ] },
        { "age" : [ "35",     "24",    "14"    ] }
    ]}

    if(
        original.network[0]['name'].length != original.network[1]['town'].length && 
        original.network[0]['name'].length != original.network[2]['age'].length 
    ) {
        console.log( 'data is not uniform' );
        return false;
    } else {
        var dataLength = original.network[0]['name'].length;
    }

    var dataString = '{"users":[REPLACETHIS]}';
    var usersString = '';

    for( i=0; i < dataLength; i++ ){
        usersString+='{"name":"'+original.network[0]['name'][i]+'","town":"'+original.network[1]['town'][i]+'","age":"'+original.network[2]['age'][i]+'"}';
        if( i < dataLength-1 ){
            usersString+=',';
        }
    }

    dataString = dataString.replace('REPLACETHIS',usersString);
    data = $.parseJSON(dataString);
</script>

After restructuring your data, you can pass it to Handlebars for templating the output.

Start by declaring your template...

<script type="text/x-handlebars-template" id="user-tmpl">
{{#users}}
    <p>
        name : {{name}} <br />
        town : {{town}} <br />
        age : {{age}} <br />
    </p>
{{/users}}
</script>

Then proceed with handlebar templating...

<script>
    var source = $('#user-tmpl').html();
    var bars = Handlebars.compile(source);
    $("#target").html(bars(data));
</script>

Once your data is structured consistently, generating the desired output becomes a straightforward process.

Answer №2

Simply reference {{key}} without the need for [index]. The #each [Object] function handles looping over the object automatically in the background.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute Cheerio selector once the page has finished loading

Hey there! I'm trying to extract the URL value of an iframe on this website: I've checked the view page source but couldn't find the iframe. Looks like it's loaded after the page is fully loaded through JavaScript. Could it be that ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

Utilizing the "apply" method with JavaScript OOP callbacks for dynamic context management

Encountering an issue while creating a callback in my custom EACH function utilizing Object-Oriented Programming principles. To achieve this, I have developed a JavaScript library that emulates the familiar habits of JQUERY. Experience it in action by ch ...

Eslint was unexpectedly unable to detect any errors in the .ts files

After creating a SvelteKit project with npm create svelte@latest, I included some .ts files for a particular library. However, when running eslint ., it fails to detect any errors. The default eslint config generated from Svelte is as follows: .eslintrc. ...

Trigger a jQuery event when a different selection is made in the dropdown menu

There are 2 choices available in the dropdown menu. <select id="_fid_140" onchange="chooseRecordPicker()" > <option value="736">9000000146</option> <option value="x3recpcker#">&lt; Browse choices... &gt;</option> Upo ...

Moving information from one controller to another, or the process of converting a controller into a service

Is there a way for me to transfer information from one controller to another? Or can I create a service from a controller? Specifically, I am looking to retrieve coordinates and store them in an object along with other variables. When I try to inject depen ...

Generating a JSON object by combining data from different JSON paths

Our task is to generate a JSON object using the provided JSONPaths. For instance, we have two paths and their corresponding values that should be included in the new JSON object: $.student.firstName = "Abc" $.student.subject['physics']. ...

Issues arise when Angular Meteor fails to load the UI-Router properly

Currently, I am exploring the integration of ui-router for routing within a meteor-angular application. My reference point is the meteor Whatsapp tutorial which can be found here Below is the relevant code snippet related to ui-router implementation: log ...

What causes the v-for in a template to only update when the input text changes?

I'm currently working on a Vue.js code, but I'm facing an issue where the template isn't updating when new data is added to the input text. My goal is for the list to update when the @click event occurs. Visit this link for reference metho ...

A guide on customizing ng-map markers by assigning colors to different categories

One of the functionalities I have allows users to see nearby locations based on their position and selected radius. These locations fall into different categories, and now I want to customize the markers' colors based on those categories. Here is a s ...

What is causing the rejection to stay suppressed?

I noticed that when function uploadLogs() is rejected, the expected rejection bubbling up to be handled by function reject(reason) does not occur. Why is this happening? In the code below, a rejection handler for function uploadLogs() successfully handles ...

I am seeking advice on how to separate words and special characters within a string

My text looks like this: String responseBody = ["{\"event\":{\"commonEventHeader\":{\"sourceId\":\"\",\"startEpochMicrosec\":\"1590633627120000\",\"eventId\":\"135.16.61.40-Fault_ ...

AngularJS: Default value causes dropdown menu text to not display

I am facing an issue with my select menu. <select id="dd" ng-show='data != null' ng-model='search'></select> Initially, I set the filter to display only USA by default. $scope.search = 'United States of America' ...

Extract the data that was returned from the AJAX post function

I am looking to create a condition that is dependent on the data received from an ajax post outside of the post function function post(){ $.post('page.php',$('#form').serialize(), function(data) { if(data !== 'good'){a ...

When errors occur while printing HTML through an Ajax request, it can hinder the functionality of other JavaScript code

I recently conducted an interesting experiment on my website. The concept involved sending an AJAX request to a PHP file, which then retrieved a random website by using various random words for search queries on Google. The retrieved website content was th ...

Setting the locale in an extended datapipe in Angular 4: A step-by-step guide

I have created a custom pipe by extending the DataPipe Angular class. import { Pipe, PipeTransform } from '@angular/core'; import { DatePipe } from '@angular/common'; @Pipe({ name: 'dateTimeFormater' }) export class DateTi ...

AngularJS's $resource module returns an empty array as a response

I am trying to display a table with items from JSON data. I have created a Service that returns the JSON data. In my controller, I am querying the Service to receive an array of data. It's a little confusing because I am putting the response in a new ...

Implementing a JavaScript file and ensuring W3C compliance

I recently purchased a template that included a javascript file in the main page with the following code: <script src="thefile.js?v=v1.9.6&sv=v0.0.1"></script> Upon inspection, I noticed there are two arguments at the end of the file ...

Storing a variable in jQuery using AJAX and retrieving it at a later time

Hey there! I'm currently using jQuery and AJAX to fetch the user ID of the logged-in user. I'm storing this information in a variable so that I can use it for some logic later on. However, I'm facing issues with accessing it. Here's my ...

The absence of a Response Entity is puzzling, especially when the server returns an Error-404 JSON

I have been working with Spring REST to manage my requests. Below is a sample of my code: RestTemplate restTemplate = new RestTemplate(); HttpEntity entity = new HttpEntity(headers); ResponseEntity<String> responseEntity = null; try { ...