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 Answer 1

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.

2
  • Seems pretty heavy handed for something simple but so far the best solution Feb 10, 2018 at 16:18
  • Agreed. Hopefully expression syntax will get a few upgrades in the future. Feb 13, 2018 at 15:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .