Lightning: aura:iteration – how to refer indexVar variable inside loop to access elements in List?

What is the way to refer index variable inside looping aura:iteration?

The code below results in error:

Failed to save undefined: expecting a positive integer, found ‘indx’
at column 10 of expression: v.labels[indx]: Source

    <aura:iteration var="item" items="{!v.items}" indexVar="indx">
        <li>
            <label class="card-detail-label">{!v.labels[indx]}</label>
            <span class="card-detail-value">{!item}</span>  
        </li>
    </aura:iteration>

Answer

It does not look like a variable defined as indexVar was meant to be used as part of another expression.

e.g. this works

<aura:iteration items="{!v.contacts}" var="item" indexVar="index">
{!index} : {!item.FirstName}<br/>
</aura:iteration>

I think in your example “item” should be changed from final value to an object which has properties .label and .value, something like this:

<aura:iteration var="item" items="{!v.items}">
        <li>
            <label class="card-detail-label">{!item.label}</label>
            <span class="card-detail-value">{!item.value}</span>  
        </li>
</aura:iteration>

Attribution
Source : Link , Question Author : Natallia , Answer Author : gaiser

Leave a Comment