I have json with an array of objects which each object has its own sub array.
I want to grab the values from _History sub array using the value in _Year variable I pass into Handlebars js. I can get it to work if I set the value directly into the code ex: {{_History.[2018].Testa}}
.
Is it possible to set the value of _Year and have handlebars get the right sub array?
The parameter values I pass to handlebars js.
var params = {
_Person: "THE JSON",
_Year: "2018"
};
JSON Code:
[
{
"_History": {
"2017": {
"Testa": "Test 1",
"Testb": "Test 2"
},
"2018": {
"Testa": "Test 3",
"Testb": "Test 4"
}
},
"FirstName": "John",
"LastName": "Doe"
},
{
"_History": {
"2017": {
"Testa": "Test 5",
"Testb": "Test 6"
},
"2018": {
"Testa": "Test 7",
"Testb": "Test 8"
}
},
"FirstName": "Susan",
"LastName": "Doe"
}
]
Handlebars JS template:
{{#each _Person}}
<tr>
<td nowrap>{{FirstName}}</td>
<td nowrap>{{LastName}}</td>
<td nowrap>{{_History.[2018].Testa}}</td> <-- Works
<td nowrap>{{_History.[../_Year].Testa}}</td> <-- Doesn't Work
<td nowrap>{{_History.[../@_Year].Testa}}</td> <-- Doesn't Work
<td nowrap>{{_History.[@../_Year].Testa}}</td> <-- Doesn't Work
</tr>
{{/each}}
Since you want to perform a dynamic lookup you will need to use the lookup helper specifically built for that.
After the dynamic lookup you will need to perform another one to access
'Testa'
or'Testb'
You can use a subexpression for this:
If you don't like using subexpressions or need a much deeper lookup I made a custom helper that it's a little easier to use:
Now you can do:
Working demo: