[SalesForce] Dynamic Field References in Lightning Component

I recently posted a question regarding a component I am building. That post has the code I will be referencing.

I have been able to make the necessary edits and now I return an sObject to the serverResult attribute, which is also listed as an object type now.

My question is this: how can I pull the correct information out of serverResult? Here is the method I am currently using:

<aura:iteration items="{!v.serverResult}" var="item">
            <li class="slds-item">
                <div class="slds-tile slds-tile--board">
                    <h3 class="slds-truncate"><a href="{! '#/sObject/' + item.Id}"> {!v.objectName}: {!item.Name}</a>  </h3>
                    <div class="slds-tile__detail slds-text-body--small">

                        <p>{!v.field1Label}: {!item.field1} <br/>
                        {!v.field2Label}: {!item.field1} <br/>
                        {!v.field3Label}: {!item.field1}</p> <br/>                            

                    </div>
                </div>
            </li>
        </aura:iteration>

I can get item.id and item.name to work perfectly because I can do a direct reference to them. The whole idea of this component is that I can use it again on a different object, and thus a different set of field references. Hence why the fields are named field1, etc.

The problem is that {!item.field1} won't return anything because (obviously) field1 is not an actual field name on that object. How can I make [field1] dynamic so I can have it actually look for the field I defined in the field1 attribute?

I tried <p>{!v.field1Label}: "{!item."+field1+"}" <br/>
and
<p>{!v.field1Label}: <ui:outputText value="{!item.'+v.field1'"/> <br/> but those are throwing an error.

Best Answer

Your best bet here would be to use a custom apex class, create the contents of that class in your apex method and finally use that on your component.

So let's say you have a custom class as:

ServerResult {
    @auraenabled 
    public string field1Label{get;set;}
    @auraenabled 
    public string field1Value{get;set;}
    @auraenabled 
    public string field2Label{get;set;}
    @auraenabled 
    public string field2Value{get;set;}
}

You can define a server method where you can fetch data as required from different object, and then create a list of this custom class as below:

@auraenabled
public static List<ServerResult> getResults() {
    List<ServerResult> myrecList = new List<ServerResult>();
    // all your custom logic to fetch records and populate this list
    return myrecList;
}

Finally, in your JS controller where you call the aura apex method, you can have it retrieved as:

// all other codes
component.set("v.serverResult", response.getReturnValue());

Finally use as you are rendering it in your component.