Implementing the rendering of a nested JSON array in a Handlebars view

I have a bunch of documents stored in MongoDB like this:

    {
    "_id" : ObjectId("5a8706973e4306202c424122"),
    "title" : "how to make a robot?",
    "description" : "arif",
    "createdBy" : ObjectId("5a71a0ebc252020d4c127911"),
    "allLearningGoals" : "my third learning goals, my fourth learning goals",
    "resources_upload" : "{\"data\":[]}",
    "participants" : "[{\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafcfbc9eee4e8e0e5a7eae6e4">[email protected]</a>\"},{\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5f4c57587e4e5c52105a5b">[email protected]</a>\"},{\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cca1adaf8caba1ada5a0e2afa3a1">[email protected]</a>\"}]",
    "createdAt" : ISODate("2018-02-24T10:15:42.548Z"),
    "__v" : 0
}

I aim to showcase each participant in a table and also utilize them for sending email notifications. The data is retrieved using mongo findById and I can view it in the console as:

console.log(data.project); // this is working fine

So in Handlebars, I can access other data like:

    {{#if data.project}}
{{ data.project.title }}
{{ data.project.description}}

But when trying to display participants, the entire array is shown:

{{ data.project.participants}} 

It displays as:

[{\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96e5e3e4d6f1fbf7fffab8f5f9fb">[email protected]</a>\"},{\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41203328270131232d6f2524">[email protected]</a>\"},{\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3cec2c0e3c4cec2cacf8dc0ccce">[email protected]</a>\"}]

How can I format it to show like this:

email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9dadcdbe9cec4c8c0c587cac6c4">[email protected]</a> 

I attempted the following:

    {{#if data.project}}
<!-- added student list-->
<div class="form-group">
    <div class="form-row">
        <div class="col-md-12">
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Email</th>
                </tr>
                </thead>
                <tbody>
                {{#each participants}}
                    <tr>
                        <td>
                            {{ this }}
                        </td>
                        <td>
                            test
                        </td>
                    </tr>
                {{/each}}
                </tbody>
            </table>
        </div>
    </div>
    <!-- added student list end -->
</div>
{{/if}}

However, it's not functioning correctly... Can someone provide some suggestions? Thank you.

Answer №1

It seems like your approach to retrieving data may need some adjustment.

<tbody>
    {{#each data.project.participants }}
     <tr>
         <td>
             <!-- -->
         </td>
         <td>
             {{ this }}
         </td>
     </tr>
   {{/each}}
</tbody>

For more information on handlebars iteration, refer to the following section: https://handlebarsjs.com/builtin_helpers.html#iteration

Answer №2

Upon fetching this data once more, I need to organize it into separate arrays for different participants:

locals.data = {
        project: [],
        participants: [],
    };    
Project.model.findById(req.params.id).exec(function (err, result) {
                    locals.data.project = result;
                    console.log(result.participants);
                    var obj = JSON.parse(result.participants);
                    console.log(obj[0]);
                    locals.data.participants = obj;
                });

Subsequently, in the handlebar view, I can display my data like so:

<table class="table table-bordered">
            <thead>
            <tr>
                <th scope="col">Name</th>
                <th scope="col">Email</th>
            </tr>
            </thead>
            <tbody>
            {{#each data.participants}}
                <tr>
                    <td>
                        {{email}}
                    </td>
                    <td>
                        test
                    </td>
                </tr>
            {{/each}}
            </tbody>
        </table>

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

Error found in Node module: SQL2 - token was not expected

Attempting to establish a connection to sql2 with the following code: const mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "abc", password: "123", database: &q ...

Presentation comparing ng-show and ng-hide efficiency

Introduction:- There may be some who opt to use ng-show instead of ng-hide="!true", while others choose ng-hide over ng-show="!true". Technically, the ng-hide directive is not necessary. However, Angular introduced it for a standard coding structure. Plea ...

Performing search operations similar to Mysql's INSTR function in MongoDB

Brand new to the world of mongo. In one of my mysql tables, I have the following fields: id (BIGINT), text (LONGTEXT) #this will have a lengthy description I am considering switching my project from Mysql to MongoDB, but before I make the leap, there is ...

Sending documents to a printer directly from a Rails application

Is there a library or gem in Rails that can be used to print the contents of a web page directly onto paper? I am curious if it's possible to specify only a specific part of the page, such as a div, for printing. Any guidance, advice, or tutorial link ...

Spinning item using a randomized matrix in Three.js

I'm in the process of creating a 3D die using Three.js that will rotate randomly when clicked, but I'm struggling to update the axis values properly. Here's where I'm currently at: <style type="text/css" media="screen"> html, ...

how to access a certain value of an object in jQuery from a JSON data

When working with jQuery, I often retrieve data in the following manner: var jsonList = '[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"}]'; var jsList = JSON.parse(jsonList); var nesels = $.trim(sel); ...

What is the best way to operate both a Django and React server concurrently?

Is it feasible to run both Django and React.js servers simultaneously? Currently, I have to individually start the Backend server using python manage.py run server and then switch to Frontend to run npm start. I am working on a Fullstack project with sepa ...

Utilizing Vuex Store in Vue for BeforeRouteEnter Hook to Interrupt Navigation

I'm in the process of configuring vue-router to verify a set of permissions before proceeding with navigation to a new route. These permissions are stored in vuex, and I am looking for a way to avoid passing them as props each time. Even though I use ...

"Freezing issue with Angular big table causing web page to lock up during

Looking for a way to improve the performance of an HTML table search function that is currently running very slowly and freezing the web page upon loading and searching. The table needs to be within the HTML file itself, not pulling data from a server. Any ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

Creating a dropdown menu in AngularJS using the ng-repeat directive

I have recently started working with AngularJS. I am trying to create three tickets using ng-repeat, each containing a dropdown list to select the number of tickets. However, I am facing an issue where the selected number is not displaying in the span. Can ...

Updates to Vue.js data are not being properly reflected in the template

This is my unique text <template> <div class="unique_class"> <div class="unique_wrapper"> <div v-for="(h, index) in heights" :key="index" class="each_bar" v-bind:style="{ height: h + 'px' }"></div> ...

Node REST back-end with Ember Data integration

My backend REST API is built using node and express, and it currently generates JSON data in the following format: [ { "id": 1, "name": "Action" }, { "id": 2, "name": "Drama" }, { "id": 3, "name": "Comedy" }, { "id": 4, "name": "Romance" } ] Howe ...

The Array JSON in Android

I'm dealing with multiple json arrays from different APIs that look like this: Array no.1: { "index0": [{ "matchId": "55", "battingTeam": "Australia", "bowlingTeam": "England" }] } Array no.2: { "onStrikePlayer ...

Display an array in C by concatenating strings, excluding the final element

As a newcomer to the world of C programming, I am faced with a challenge of printing an array separated by commas, but without printing the last comma. The code snippet I have tried so far is as follows: void p_array(const int array[], const int s) { fo ...

What are the steps to check Drag and Drop functionality using Selenium IDE?

I've been working on implementing tables with jQuery UI's sortable feature, but I'm struggling to come up with a way to test it using Selenium IDE. After searching for a solution, I came across this helpful post: How to test a JQuery UI Sor ...

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

The display of prime numbers is not functioning in this JavaScript code

I've been diving into JavaScript lately and I'm currently working on displaying prime numbers. However, I'm encountering an issue where the output is not showing up. Can someone lend a hand? I seem to be stuck. Here is my initial code snipp ...

Generating variables from array elements

I created two functions, one that retrieves folder names and saves them in an array, and another that retrieves image file names and also saves them in an array. Is it possible to have a loop that iterates over the folder names and assigns each file name ...

Is there a simple way to transfer all the form data to a new popup window using javascript?

I'm looking to create a printer-friendly version of a form in a new popup window. I'm wondering if there is a simple way to pass all of the form data to the popup, potentially by passing the form itself. Any advice on how to achieve this would be ...