Is it possible to use Handlebar.js to loop through and showcase the key-value pairs of a JSON object?

Having recently delved into the world of javascript, I came across handleBar.js as a tool for templating with dynamic data.

I experimented with a sample that functioned smoothly, and the json structure was uncomplicated and easy to understand.

(function()
  {

    var wtsource = $("#some-template").html(); 
    var wtTemplate = Handlebars.compile(wtsource); 


var data = { users: [
      {url: "index.html", name: "Home" },
      {url: "aboutus.html", name: "About Us"},
      {url: "contact.html", name: "Contact"}
    ]};

Handlebars.registerHelper('iter', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";

if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
  ret = ret + fn($.extend({}, context[i], { i: i, iPlus1: i + 1 }));
}
} else {
ret = inverse(this);
}
return ret;
});

var temp=wtTemplate(data);
$("#content").html(temp);

})();


  <script id="some-template" type="text/x-handlebars-template">
  {{#iter users}}
 <li>
    <a href="{{url}}">{{name}}</a>
 </li>
 {{/iter}}

</script>

I am now faced with the question of how to iterate through a json structure similar to the one below. Any suggestions on how to achieve this would be greatly appreciated:

var newData = { "NEARBY_LIST": {

        "100": {
            "RestaurantID": 100,
            "ParentRestaurantID": 0,
            "RestaurantName": "Chennai Tiffin",
            "listTime": [{
                    "startTime": "10:00",
                    "closeTime": "23:30"
                } ]
        },

        "101": {
            "RestaurantID": 101,
            "ParentRestaurantID": 0,
            "RestaurantName": "Biriyani Factory",
            "listTime": [{
                    "startTime": "11:00",
                    "closeTime": "22:00"
                }]
        }

    }
};

Answer №1

When it comes to accessing the properties of an object, Handlebars is not involved. If you are working with JSON data and want to access it using bracket or dot notation, you need to first parse the JSON into a JavaScript object using the JSON.parse() function.

Once you have successfully parsed the JSON, you can access its properties like this:

var property = myData['CATEGORY']['200'].ProductName; // "Example Product"

Check out this code snippet for a demonstration.

http://jsfiddle.net/abcdefg/3/

Answer №2

I'm a bit unsure of your exact meaning, but if you're wondering how to utilize or interpret the data in newData, here's a suggestion:

newData = JSON.parse(newData); //converts the JSON into a JavaScript object

You can then access the object in this manner:

newData.NEARBY_LIST //the object that holds the array
newData.NEARBY_LIST[0] //the first element (with key "100")
newData.NEARBY_LIST[1] //the second element (with key "101")
newData.NEARBY_LIST[0][0] //the initial field of the first element (with key "RestaurantID", value "100")
newData.NEARBY_LIST[0][2] //the third field of the first element (with key "RestaurantName", value "Chennai Tiffin")
newData.NEARBY_LIST[0][3][0] //the first field of the fourth field of the first element (with key "startTime", value "11:00")

I hope this information aligns with your needs.

EDIT: If you are not using arrays, like Siddharth has mentioned, you can access properties by treating them as if they were in an associative array (e.g. newData["NEARBY_LIST"]["100"]. Technically speaking, JavaScript does not support associative arrays. These properties may also be accessed as newData.NEARBY_LIST, although I advise against it in this scenario as property names cannot begin with numbers. Thus, using a variety of notations is not recommended).

In this context, I recommend utilizing arrays since they simplify numerous actions (such as length checks) and come with virtually no drawbacks.

EDIT2: Additionally, I urge you to maintain consistent camelCasing conventions throughout your codebase. Your current mix of properties/variables starting with capital letters (e.g. "RestaurantName", "RestaurantID") and others in lowerCamelCase (e.g. "listTime", "startTime") could lead to errors among you and your colleagues.

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

Ensure that the flex item spans the entire width of the page

I'm struggling to make my audio-player resize properly to fit the full width of my page. I can't seem to figure out what I'm missing or doing wrong... (Current Look) https://i.sstatic.net/tEtqA.png I'm attempting to utilize HTML cust ...

Cypress' clicking feature does not automatically scroll into view

A new website has been constructed using a combination of Vue/Nuxt and includes SSR, with links located in the footer. During testing, it was discovered that although the link is present and visible, when attempting to click on it, the error message click ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

Retrieve the date information from the <td> element, if it exists

There are numerous rows in the table. The table cell labeled "dates" may contain either a specific date or the word "Permanent". If there is a date present and it happens to be greater than today's date, it needs to be highlighted in red. I attempted ...

What is the best way to merge two JSON objects linked by a foreign key in Angular?

Looking to display data from two JSON objects in a table, connected by a foreign key. The first set of JSON data is as follows: $scope.items = [ {status_id: 1, type: 1}, {status_id: 2, type: 2}, {status_id: 1, type: 3}, {status_id: 1, typ ...

Encountering an issue where the Angular build is unable to locate the installed Font-Awesome node module

Every time I attempt to compile my project using ng build --prod, I encounter the following error: ERROR in ./src/styles.scss Module build failed: ModuleBuildError: Module build failed: Error: Can't resolve '~font-awesome/css/font-awesom ...

Is there a way to navigate to a newly created document?

Is there a way to automatically redirect a user to the show action of a document or post they have just created using express.js? Take a look at the following code snippet, which outlines how I am creating the document: app.post('/document/create&ap ...

Customize chrome's default shortcuts with JavaScript

I'm working on an application that requires me to override some shortcut keys in the Chrome browser. While I'm able to create custom shortcuts to trigger alerts like in this Stackblitz example, I'm having trouble overriding a few default sho ...

What could be causing my site's PDF generation process to block other AJAX processes?

I am working on an MVC3 application that needs to generate extensive reports regularly. Users can select their criteria and request the report, which currently opens in a new tab/window using the Javascript window.open() method. However, while the report i ...

What is the best way to calculate the total duration (hh:mm) of all TR elements using jQuery?

I currently have 3 input fields. The first input field contains the start time, the second input field contains the end time, and the third input field contains the duration between the start and end times in HH:mm format. My goal is to sum up all the dur ...

Assign a value to a variable within the $_POST array for validation purposes using Codeigniter

I am currently developing a WebSocket based application using Codeigniter. The data is being received as a JSON string (not via a POST Method) and I want to utilize Codeigniter's built-in form_validation method to validate this JSON data. Here are th ...

Troubleshooting the Angular Fullstack + CORS issue: "XMLHttpRequest cannot load

I've been wracking my brain trying to figure this out. Utilizing the yeoman generator angular-fullstack, I created a simple Angular app on a NodeJS server with Express. The app makes remote service calls, so there are no API server side calls within ...

How can I translate JSON in a Jbuilder template using Rails 4?

I am currently working on a file named 'show.json.jbuilder' in which I have included the following content: json.extract! @person, :id, :first_name, :last_name, :title, :birthday, :gender, :created_at, :updated_at While translating this content ...

Mastering the Art of Dynamically Assigning Types in TypeScript

Recently, I encountered a challenge with wrapper function types. I am looking to convert functions with callbacks into promise-based functions. Most of these functions have a similar structure: func({ success:...., fail:...., complete:... }) So, I ...

The Javascript function is malfunctioning, unable to assign the 'onclick' property to null

Here's the code snippet I'm working with: var exit = document.getElementById("exit"); exit.onclick = function() { "use strict"; document.getElementById("fadedDiv").style.display = "none" ; }; However, when I check the console, it shows ...

Error: EPERM - Sorry, cannot perform operation, unable to access TestAutomationcypress.json'

When attempting to execute the Test Runner for Cypress for the first time using the command - node_modules.bin\cypress open An unexpected error is encountered - Error: EPERM: operation not allowed, opening \TestAutomation\cypress.json' ...

The express-handlebars module is having trouble parsing HTML within the main layout file in an Express.js application

Hello, I am facing an issue with handlebars as it is not reading the HTML in my file. Here is a screenshot highlighting the problem along with the provided code. The folder structure is as follows: views layouts main-layout.hbs home.hbs https://i ...

Setting the default time zone to UTC for Material UI date and time picker

Looking to implement a dialog in React with Material UI for users to input start and end date/time. The goal is to have the default start set to the beginning of the current day and the default end set to the end of the current day (UTC). However, I'm ...

Adjust the hue of a Three.js-generated 3D cube

Seeking assistance! How can I customize the colors of a 3D cube in the Three.js library rather than using the default settings? This is what I have managed to create so far - HTML <div id="container"></div> JavaScript // revolutions per se ...

What causes the div to shift while performing the FadeIn-FadeOut effect?

It seems like there might be something that I'm overlooking, as I am encountering a minor issue with this. I am aiming to align the "submenu div" on the right side of the Show/hide links. Initially, when I load the div, it is correctly positioned. H ...