1

I would like to have a filtered version of a collection as the source data of an aura iteration. Basically, something like this:

<aura:iteration items="{! v.myList.filter(element => ....) }" var="item">

Is this possible and if not, what can I do to achieve the same? Any advice is much appreciated. Thanks.

  • you could try writing filter logic in controller/helper and use that list in comp. – Ysr Shk Sep 30 at 9:06
  • Here's a full example that I wrote some time back, in addition to the answers you've received that may help you. – sfdcfox Sep 30 at 9:22
5

You cannot do this in salesforce lightning - Aura or LWC. Below are the options that works in salesforce lightning Aura

Option 1: Have filtered logic in Javascript and use it in Component. This is preferred.

CONTROLLER:

let myFullObject = {
    myList: [...],
};
myFullObject.myFilteredList = myFullObject.myList.filter(element => ...);
component.set("v.myFullObject", myFullObject);

COMPONENT:

<aura:iteration items="{! v.myFullObject.myFilteredList }" var="item">
    <!-- ... -->
</aura:iteration>

Option 2: You can use conditional rendering inside iteration. Option 1 is preferred as this option will have performance issues as Aura_Prod library has to filter it in HTML directly but before filtering, it runs numerous functions on whole list.

<aura:iteration items="{! v.myList }" var="item">
    <aura:if isTrue="{! item.someVal=='myVal' }" >
        <!-- ... -->
    </aura:if>
</aura:iteration>
  • Thanks for your comment. I concur that the first method is preferable but I think in my specific case, the second option might be more applicable. If I were to create such a filtered list in the controller and save it in some aura attribute, would it be possible to use something like <aura:if isTrue="{! v.filteredList.includes(item) }" > as a test? I am not too sure what logic is allowed in an aura:if. – user73893 Oct 1 at 0:40
  • @user73893, you can use Comparison Functions from developer.salesforce.com/docs/atlas.en-us.lightning.meta/… – salesforce-sas Oct 1 at 2:00
0

I would recommend doing any operation on array should be handled in JS.

aura:iteration iterates over a collection of items and renders the body of the tag for each item. Data changes in the collection are rerendered automatically on the page. It also supports iterations containing components that are created exclusively on the client-side or components that have server-side dependencies.Documentation

you can use indexVar conditional render UI, this should return the index of List

 <aura:iteration items="1,2,3,4,5" var="item" indexVar="index">  
    <meter value="{!item / 5}"/><br/>
</aura:iteration>

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.