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

Enzyme examination: Error - anticipate(...).find was not recognized as a function

What is the reason for .find not being recognized as a function in the code snippet below? import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import { AuthorizedRoutesJest } from ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Is it necessary to have the script tag as the first tag in the body of the HTML?

I have a script file that needs to be included by third party implementors on their web pages. It is crucial for this script to be the first tag within the body element, like so: <body> <script type="text/javascript" src="/my_script.js"></ ...

What is the best way to empty a backbone collection in preparation for loading new data?

Hey everyone, I've been working on a Backbone application that involves adding and deleting or editing images. Currently, I'm using a router to navigate between different sections like the gallery and forms. However, whenever I make changes in th ...

Is there a way to extract tweet text from a json file for advanced analysis?

I have implemented a code snippet that utilizes the Twitter API to retrieve tweets based on a user-input search term and save them in a JSON file. My main focus is solely on extracting the actual tweet text and discarding any other information. Could you ...

Searching across multiple attributes in Jquery UI Autocomplete: A comprehensive guide

My data is stored in an array of objects with a structure similar to this: $scope.usersList = [{ "name": "John", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09a9f989eb088898ade939f9d">[email protected ...

The JavaScript animations in AngularJS using ng-class are not being activated

I've been attempting to apply js-defined animations to the ng-class directive using the standard syntax of add and remove, but for some reason, the animations are not running. After checking the logs, it seems that the add and remove functions are not ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...

Reveal unseen information on the webpage upon clicking a link

I have successfully implemented a fixed header and footer on my webpage. The goal is to make it so that when a user clicks on a link in either the header or footer, the content of that page should appear dynamically. While I have explored various styles, ...

Using JavaScript to detect the Facebook like button on a webpage

I am currently developing an application for Facebook using HTML and Javascript. My goal is to be able to detect when a user clicks the "Like" button on my company's Facebook page without needing to embed a separate "Like" button within my app itself. ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Get rid of the percentage displayed in the tooltip of a Google Pie Chart

Is it Possible to Exclude the Percentage from Google Charts Tooltip? For instance, I am looking to eliminate the display of 33.33% in the tooltip and only show the value itself. ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

Guide on retrieving data from an axios promise in JavaScript

I am struggling to manage the output of multiple lists retrieved through an axios API call made in JavaScript. I want to know how to effectively log the results and save them for future use, particularly for creating a data visualization. Here is my curre ...