Retrieve specific items from a handlebars array by using the loop index

Utilizing handlebars.js, I am iterating through the categories and then accessing an element in the series array using the current array index. This is achieved with the following helper function.

var json={
    "categories": [{
            "id": 3,
            "name": "category 0"
        }, {
            "id": 6,
            "name": "category 1"
        }
    ],
    "series": [{
            "id": 1,
            "name": "DUMMY",
            "data": [{
                    "id": 5,
                    "name": "series 0 data 0"
                }, {
                    "id": 10,
                    "name": "series 0 data 1"
                }
            ]
        }
    ]
}

Handlebars.registerHelper('getArrayValues', function(ar, index, prop) {
    return ar[0].data[index][prop];
});

var template = Handlebars.compile(json);

{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id with helper: {{getArrayValues ../series @index 'id' }}</p>
<p>series name with helper: {{getArrayValues ../series @index 'name' }}</p>
{{/each}}

Is it possible to achieve this without a helper function? Here is my attempt where I tried to access the properties that the lookup function returns but seem to face issues.

{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id: {{../series.[0].data.[@index].id}}</p>
<p>series name: {{../series.[0].data.[@index].name}}</p>
{{/each}}

Answer №1

I discovered a solution for this issue, although I'm not sure how effective it is, but it's working perfectly

Give this a try :)

{{#each categories}}
  <p>id: {{this.id}}</p>
  <p>name: {{this.name}}</p>
  <p>series id with helper:{{#with (lookup  ../series.[0].data 
  @index) }}{{this.id}}{{/with}}</p>
  <p>series name with helper: {{#with (lookup  ../series.[0].data 
  @index) }}{{this.name}}{{/with}}</p>
{{/each}}

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 using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

javascript categorize data by key and display in a tabular format

I have a Client ID and gender information available. Shown below is a JSON response along with a JavaScript function to display the data in a table format. The JSON response structure is as follows: studies = [{ "id": { "Value&qu ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Utilizing jQuery: How to pass the $this object along with additional parameters to a

Is there a way to pass the value of this along with other parameters to a function? I have attempted the following methods, but they have not been successful: function update_alt($this, my_param){ this_alt = $(this).attr('alt'); ...

New to jQuery and struggling to download or link it for the first time?

My attempt to download the uncompressed version of jQuery from the jQuery download page did not go smoothly. When I clicked on the bottom left download button, it started to download but then a dialog box appeared asking for permission. After accepting, an ...

What could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

Ways to attach JQuery UI Sortable widget to html content fetched through Ajax requests?

Here's a straightforward question for you. Take a look at my JavaScript/jQuery code snippet below: $('body .combo-table').sortable({ handle: '.grabber', opacity: 0.9, axis: 'y', start: function (e, ui) { ...

There seems to be an issue with locating the module '/opt/repo/ROOT/server.js'

Error in server.js on jelastic node.log file When attempting to publish a simple page created with Bootstrap using nodejs express and ejs, the server is returning a 504 Gateway timeout error and the application cannot run. The node.js log file is displayi ...

Ensuring the length of a Multidimensional Array

Today I decided to delve into coding with Google Sheets and JavaScript. As I was working on a project, I encountered a small issue: function myFunction() { var sheet = SpreadsheetApp.getActiveSheet(); var data = sheet.getDataRange().getValues(); fo ...

Upon completion of the function, the ForEach loop commences

I'm encountering an issue with my code. I am trying to verify if there is an item in the cutlist array that has a material_id which does not exist in the materials database. However, the code within the forEach loop is being executed after the functio ...

What is the term used to describe the way console.log styles the Json object?

Have you ever noticed that when a JSON object is printed, say in a script run by node using console.log, it doesn't exactly pretty print the JSON? It sort of strikes a balance between showing as few lines as possible while still maintaining readabilit ...

Turn off the chrome react DevTools when deploying to production to ensure the

I have successfully browserified my react app for production using gulp and envify to set up NODE_ENV. This has allowed me to remove react warnings, error reporting in the console, and even disable some features like the require of react-addons-perf. Afte ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

javascript - Alternate text colors several times within specified color ranges

Seeking assistance with changing the text color multiple times from #627CA9 to #FFFFFF and vice versa. Here's what I've tried: function changeColor(id) { var x = document.getElementById(id); if (document.getElementById(id).style.color = " ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

Navigating data attributes with jQuery

I'm encountering some difficulties with the following code, and I'd appreciate some guidance on the process, please. Below is the HTML snippet: <span data-credit-name="Name_1"><strong>1</strong> Name 1</span><br /> ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

How can BitSet be utilized to eliminate repetitive elements from an Array?

I am working to comprehend the application of the following statement that I came across on Stack Overflow You can utilize BitSet, by traversing the array of values and setting the corresponding bit to true. Then you can iterate over the bit set and disp ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

Seeking ways to access a nested array object within an array object in React Native

Array [ Object { "resultlist": Array [ Object { "img": "https://www.act.com/image/cache/catalog/new%20thumbnails/Mifa%20A1BlacjkThumbnail-600x600.jpg", "name": "Mifa F1", "product_id": 87, "type": "product", ...