Retrieving values from an array or object using a key inside a handlebars mustache

I've been struggling to find a solution for this. Despite trying subexpressions and various suggestions from StackOverflow, none of them seem to work because they require me to know the key in advance.

Here is the object I'm working with:

{
    fields: {
        1: {
            complete: 1,
            submitted: 0
        },
        2: {
            complete: 1,
            submitted: 0
        }
}

And so on.

Within my Handlebars template, I'm iterating through an array of objects. Each object in the array includes a field_id key that corresponds to a number found in the structure above.

My goal is to access the variables within the array structure based on the current field_id being iterated. I've attempted different syntaxes like:

{{fields[(field_id)].complete}}

{{fields[{{field_id}}].complete}}

{{fields.(field_id).complete}}

{{fields.({{field_id}}).complete}}

But unfortunately, none of them are successful.

Is there a way to achieve this?

Answer №1

I prefer not to create a custom helper for this task. Instead, I would opt to utilize the existing Lookup helper in conjunction with the with block helper:

{{#with (lookup fields field_id) as |field|}}
    {{field.complete}}
{{/with}}

Another approach could be to use the lookup helper with a subexpression:

{{lookup (lookup fields field_id) 'complete'}}

Answer №2

To achieve the desired functionality, I created a custom helper method:

Handlebars.registerHelper( 'retrieveFieldValue', function ( inputData, fieldID, keyValue ) {
    var value = ( inputData[ fieldID ] ) ? inputData[ fieldID ][ keyValue ] : '';
    return value;
} );

After registering the custom helper, I utilized it within my templates like so:

{{retrieveFieldValue dataObject fieldID 'value'}}

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

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet. Here is the HTML CODE snippet: <!DOCTYPE HTML> < ...

Lack of element content in AngularJS unit testing

I am currently working with AngularJS 1.5+, jasmine, and karma, and I am facing an issue when testing a component along with its template. When the component's template is compiled, it seems to be missing the expected content. Here is a snippet of th ...

Issue with react-intl not updating the placeholder value

Is there an error in my implementation? I have utilized the intl.formatMessage() API (https://github.com/yahoo/react-intl/wiki/API#formatmessage) in this manner: this.intl.formatMessage({id:'downloadRequest.success',values:{correlID:'test& ...

Is there a way to condense an array containing duplicate elements by adding together their second value using lodash/underscore?

How can we transform the following array [ {name: "a", weight: 1}, {name: "b", weight: 3}, {name: "a", weight: 5}, {name: "b", weight: 7} ] into this array where duplicate weights are summed up? [ {name: "a", weight: 6}, {name ...

Experience a captivating Angular slideshow carousel that resets when you click on a dot button, all powered by the magical capabilities of

Check out this Stackblitz Link for a working sample. I have developed an angular carousel slider component using rxjs. Each slide changes after 5 seconds and everything is working smoothly. However, I am facing an issue where clicking on a particular dot ...

The JavaScript Date() string that was inserted into the database is now elegantly displayed

Can you help me figure out how to format a date string that's stored in a database like this: 2016-09-13T18:18:08.518Z, into a more visually appealing format such as: 13 September 2016? Thank you in advance! ...

I continue to encounter a TypeError when using the mongoose-paginate function

Every time I try to run my code, I encounter the following error message: TypeError undefined paginate function Below is the snippet of code causing the issue: var mongoose = require('mongoose'); var mongoosastic = require('mongoosastic ...

Troubleshoot: React and Laravel login authentication issues

I am relatively new to working with React, React Router, and Laravel for authentication. I've been trying to set up authentication using Laravel, React, and React Router, and although the page redirects to the desired destination when the submit butto ...

Performing string operations using an array of strings

I have an array of strings as shown below ["i.was.wen.the.coding", "i.am.wen.to", "i.am.new", "i.am", "i"] Each sentence in the array can be split by a period (.). I am looking to create a logical algorithm pattern to reconstruct a meaningful sentence by ...

Is it possible to use automation tools like QTP or Selenium to automate a Siebel application built on the High Interactivity framework?

I am looking to automate a Siebel application that uses the Siebel HI framework. I have attempted using both QTP and Selenium, but unfortunately, I am facing issues with object recognition, particularly with tables. Is there anyone who can offer assistan ...

How can I use React to switch the visibility of a nested component from the parent container component?

Objective I am in the process of replicating a List Control Component using React and Redux, following the guidelines outlined in Google Material Design layout. This list control will enable users to create, rename, and delete items within the list witho ...

Adding a clickable button to execute code within a LeafletJS marker!

I'm currently experimenting with adding a button inside a pointer that will log a message to the console. This is simply a test to see if I can execute a method on the marker, but so far I haven't been able to display any text. const marker = L.m ...

Issues with transmitting data from client to server through Socket.io

Experiencing a communication glitch between the client and server when using socket.io. Sending JSON object: loginInfo = { email: 'username', password: 'password' } Client side code: socket.emit('user:login', loginInfo); ...

Implementation of SpotLight rotation using three.js

Currently, I am attempting to rotate a spotlight using the following code: var light = new THREE.SpotLight( color, intensity, distance ); light.position.set( 0, 100, 0 ); light.rotation.set( 0, Math.PI, 0 ); light.shadowCameraFar = 50; light.shadowCamer ...

Vue3 - Managing the Enabling and Disabling of Text Input and Checkbox Based on Input Number

<div class="container-body" v-for="index in 10" :key="index"> <div class="container-content"></div> <div class="container-content"> <input :id="'Row&apo ...

Error: We are facing an issue with new.mongoose.Schema as it is not functioning properly and

I am experiencing an issue with my product.js file. It keeps throwing an error about an unidentified identifier, and whenever I try to fix one problem, another one pops up. I have been struggling to locate the root cause of this error. ...

Is there a way to coordinate CSS animations with JavaScript intervals?

Is there a reliable method to synchronize an interval function called by a useEffect in a React app and a css animation? I have set the interval for every 4 seconds, matching the duration of the animation. However, it seems that they are not always perfe ...

Preserve the location of a moveable div using jQuery

I have implemented draggable divs in my JSP page, allowing users to move them around freely. After dragging the divs, I would like to save their positions either in a cookie or database for future reference. Could you please advise on the best way to ach ...

Assistance with Constructing Multi-Dimensional Array Using For Loop in PHP

As someone relatively new to PHP and web development, I'm facing some difficulties figuring out the best approach to program a multi-dimensional array in PHP using for loops. The project at hand involves creating a review website. Bootstrap is used t ...