Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache.js getting current Index of an array

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

  • with the array index such as
    {{#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;
    
  • like image 756
    Ravi Ram Avatar asked May 03 '13 14:05

    Ravi Ram


    People also ask

    How do you find the index of an element in an array in JS?

    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.

    How do you find the index of an element in an array?

    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.

    What is the start index of an array?

    Referring to array elements The index of the elements begins with zero.


    1 Answers

    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}}
    
    like image 102
    Luca Avatar answered Sep 21 '22 10:09

    Luca