4

I have a component...

<aura:component>
    <aura:attribute name="myArray" type="Object" />
    <aura:attribute name="index" type="Integer" default="0" />
    ...

    {!v.myArray[v.index]}
</aura:component>

Saving this markup fails with...

Failed to save undefined: expecting a positive integer, found 'v' at column 9 of expression: v.myArray[v.index]: Source

...as I can't access the array using the index attribute. Why that and which alternative do I have?

5

You can't. I've asked the same question a while ago in a map context:

Using a Map type attribute in aura:if

What you could do though is use an aura:iteration to run over the array, and inside render components with an index/value variable to be passed from the iteration, and have the component do the logic inside based on the index/value passed.

Iteration:

<aura:iteration items="{!v.myarray}" var="someVar" indexVar="someIndex" >
  <c:someComponent aValue="{!someVar}" anIndex="{!someIndex}" />
</aura:iteration>

Inner component:

<aura:component>
  <aura:attribute name="aValue" type="String" />
  <aura:attribute name="anIndex" type="Integer" />
  <div>
    {!v.aValue}
    {!v.anIndex}
  </div>
</aura:component>

Alternatively, you could read the array in an init/change event and set the result in an attribute:

Markup:

<aura:component>
    <aura:attribute name="myArray" type="Object" />
    <aura:attribute name="index" type="Integer" default="0" />
    <aura:attribute name="value" type="String" />
    <aura:handler name="change" value="{!v.index}" action={!c.accessArray}" />
    ...

    {!v.value}
</aura:component>

Controller:

accessArray : function(component) {
    var myArray = component.get('v.myArray');
    var index = component.get('v.index');
    component.set('v.value', myArray[index]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.