Send a JSON array to the underscore template

I'm struggling to make this work, even though I feel like it should be possible. What I am trying to do is use underscore and jQuery to apply a template to an array of objects. Here is the code snippet that I have:

var template = _.template($("script.template").html());
var jA = data.jsonArray;
$("#results").html(_.template(template(jA)));

My expectation was that the template would be applied to each object in the array, but unfortunately, it's not working as expected.

When I tried using a loop, it worked fine, but it seems like an unnecessary step.

$.each(jA, function(index,value){
   $("#results").append(_.template(template(value)));
});

Is there something I'm missing that's causing this issue, or do I really have to resort to using a loop? (jA is confirmed to be a JSON array)

Thank you for your help :)

Answer №1

A loop is necessary in this case, as Underscore does not automatically iterate and add the processed template repeatedly just because an array is provided. It's important to consider scenarios where a template requires specific data from an indexed element in a list, such as <%= data[0] %>.

Fortunately, implementing the loop is straightforward:

_.each(data, function(element) {
  container.append(template(element));
});

If you need more guidance, feel free to check out this example on CodePen.

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

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

What is the best way to initiate a page refresh from a separate component in ReactJS?

As a newcomer to React, I am facing an issue in my CRUD application. I have a Main component and in the List Component, I need to fetch data from the server using an API call. The problem arises when I submit a new item in the Create component - I have to ...

JavaScript - Clear the localStorage when closing the final tab of a website

Currently, I am working with AngularJS and utilizing $window.localStorage to store the username of a logged-in user. Since localStorage needs to be explicitly deleted, I have implemented an event listener for $(window).on('unload', function(){}) ...

Error: Could not locate the module "../aws-exports"

Currently, as I work on building my project on Amplify hosting, I have encountered a front-end build issue. The technology stack I am using is Next.js. Error: ./src/pages/_app.js Module not found: Can't resolve '../aws-exports' in '/c ...

Troubleshooting Heroku: Resolving Node Module Errors Despite Installation Status

Currently, I am trying to set up node and Heroku but have encountered a roadblock early on. Despite following this particular guide, I am unable to view my Heroku app locally. Upon running heroku local web and visiting localhost:5000, an error is displa ...

Tips for sorting through JSON data in a URL

What is the best way to sort through JSON data from a database based on a specific field? Below is an example of the JSON data: [ { "Car_No":"25", "Car_Model":"car1", "Car_Type":"car2", "Capacity":"12", "Image" ...

Unraveling JSON data in PySpark by handling multiple array fields

Seeking a solution to flatten Json data with arrays (list of dictionaries), where one array field (version) becomes a parameter for columns. The initial dataframe created from Json appears as follows: -id (string) -as_of_date (string) -past_features (array ...

Transforming cURL output to JSON format

I'm currently attempting to utilize a cURL method for sending POST data to an external server with the requirement that it returns data formatted in JSON code. Currently, the only format being returned is XML which is not suitable for further processi ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

Getting the document ID from a faunaDb query: a step-by-step guide

One array that I am dealing with consists of the following: [ Ref(Collection("twitch_users"), "280881231730573837") ] My goal is to extract the string of numbers from this array and utilize it in another function within my codebase. Ho ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

What is the proper method for sending parameters in JSON within a data object?

On my aspx page, I have a text box where I need to retrieve the text and pass it to a function as JSON data. To achieve this, I have a server-side method. [WebMethod] public static OfficeDetails[] BindSearchDatatable(string officename) { DataTable dt ...

Learn the process of copying and pasting a file in PhoneGap with the help of JavaScript

I am currently working on a mobile application using the phoneGap framework. I have placed my existing .db file in the www directory of phoneGap. I need to copy this file from the www directory to the internal memory of the application at /data/data/applic ...

The JS object was successfully retrieved, but unfortunately the responseText is not functioning

After making a call to a method that simply returns a string, my post request is returning an object with a string in the responseText field. However, when I try to access d.responseText, it shows up as "undefined." Can anyone provide insight into why th ...

Utilizing commonjs pattern to share functions among different couchdb views for increased reusability

I am seeking a way to utilize a variety of functions across different couchdb view map functions. My attempt involves using the commonjs require pattern. Within the given design doc, I am puzzled as to why the require statement in test1 successfully funct ...

Performing an Ajax Get Request in Rails 4 without rendering a view

Welcome to a unique question that has been carefully crafted to stand out from the rest. After hours of dedicated research, it seems like the right terms are still eluding me. In the world of Rails 4, my aim is to utilize an ajax request to fetch data fro ...

The angular view is lacking a CSS class

index.html: <div ng-view="myview.html"></div> myview.html: <table class="table table-striped table-hover"> <tr> <td>Name</td> <td>Product</td> </tr> <tr ng-repeat="deal in deals" class="clickableR ...

Attempting to retrieve information from JSON or JSONP through the utilization of the WOT API

Recently, I utilized the WOT (web of trust) API and encountered a response structured like this: process( { "www.google.com": { "target": "google.com", "0": [ 95, 84 ], "1": [ 95, 84 ], "2": [ 95, 84 ], "4" ...

The web server is crawling at a snail's pace, even though the CPU usage is barely registering at 0-5% and RAM

After successfully coding a web chat that updated with new messages via ajax every second, I encountered a major issue. The website started to lag and eventually crashed when there were approximately 10 users online. It turned out the problem was caused by ...

Implementation of Material UI Autocomplete feature with options consisting of an array of objects linking to both ID and label properties

Utilizing the Material UI Autocomplete component in my project has been a key feature. Referencing the official documentation, here are the available options: let options = [ { id: "507f191e810c19729de860ea", label: "London" }, { id: "u07f1u1e810c19 ...