7

In a lightning component I would like to be able to reference an objects property dynamically. I'm wondering if there is a way to do this in an expression. In javascript it's easy myObject[myVar] but this doesn't seem to work in lightning expressions

<aura:iteration items="{!v.accounts}" var="account" >
  <tr>
    <aura:iteration items="{!v.fields}" var="field">
      <td>{!account[field]}</td>
    </aura:iteration>
  </tr>
</aura:iteration>

I would like to avoid using a custom renderer.

1

It is currently not possible with expression syntax, but you can achieve it with a small component that outputs the given field's value (no custom renderer necessary).

Your example would then be:

<aura:iteration items="{!v.accounts}" var="account" >
  <tr>
    <aura:iteration items="{!v.fields}" var="field">
      <td><c:outputField object="{!account}" fieldName="{!field}"/></td>
    </aura:iteration>
  </tr>
</aura:iteration>

<!-- c:outputField.cmp -->
<aura:component>
  <aura:attribute name="object" type="Object" />
  <aura:attribute name="fieldName" type="String" />
  <aura:attribute name="fieldVal" type="String" access="private" />

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

Where the outputField component computes (and/or formats) the fieldVal in the init event handler.

  • Seems pretty heavy handed for something simple but so far the best solution – Scott Morrison Feb 10 '18 at 16:18
  • Agreed. Hopefully expression syntax will get a few upgrades in the future. – Pawel Fronczak Feb 13 '18 at 15:54

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.