On initial page load, we are loading a large json data object with news feeds. We are using Mustache.js and listing all the new feed headlines which is working great.
We have a div area to display the details of the onClick news item. Since we have the data already loaded, I need to pass the index of the current item (array index) to grab the news item we need to get details from.
{{#Data}}
<li>
{{eventName}}<br />
{{eventLocName}}<br />
{{eventLocCity}}, {{eventLocST}}
</li>
{{/Data}}
I would like to add an id to the
{{#Data}}
<li id='{{Data.index}}'>
{{eventName}}<br />
{{eventLocName}}<br />
{{eventLocCity}}, {{eventLocST}}
</li>
{{/Data}}
What is the syntax to get array index into my Mustache.js template?
UPDATED / WORKING
Once I get my results
onto the DOM, I used the following JS to add the 'index
' into each array item. (select answer below code helped)
for (i in result)
result[i].index = i;
JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Referring to array elements The index of the elements begins with zero.
I'm sorry... I think you need to manually add index:
for (i in Data)
Data[i].index = i;
and
{{#Data}}
<li id='{{index}}'>
{{eventName}}<br />
{{eventLocName}}<br />
{{eventLocCity}}, {{eventLocST}}
</li>
{{/Data}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With