Lightning aura:iteration over two objects with dynamic key
In this example I am using contact object and we will get contact' Account info as well as owner info..
For now I am hard-coded API name but you can use Field set as well..
Apex class
public class GetAFewContacts {
@AuraEnabled
public static list<Contact> getContacts(){
return [SELECT Id, Name, Account.Name, Owner.Name, Owner.Email
FROM Contact LIMIT 10];
}
}
Component
<aura:component controller="GetAFewContacts" implements="force:appHostable, flexipage:availableForAllPageTypes, forceCommunity:availableForAllPageTypes" access="global">
<aura:attribute name="contacts" type="Contact[]" />
<aura:attribute name="fieldNames" type="String[]" default='["Id","Name", "Account.Name", "Owner.Name", "Owner.Email"]'/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<table>
<tr>
<aura:iteration items="{!v.fieldNames}" var="fieldName">
<th><ui:outputText value="{!fieldName}" /></th>
</aura:iteration>
</tr>
<aura:iteration items="{!v.contacts}" var="contact" >
<tr>
<aura:iteration items="{!v.fieldNames}" var="fieldName">
<td>
<c:ContactAndFieldName contact="{!contact}" fieldName="{!fieldName}" />
</td>
</aura:iteration>
</tr>
</aura:iteration>
</table>
</aura:component>
ControllerJS
({
doInit : function(component, event, helper) {
var action = component.get("c.getContacts");
action.setCallback(this,function(response){
if (response.getState() === "SUCCESS"){
component.set("{!v.contacts}",response.getReturnValue());
}
}
);
$A.enqueueAction(action);
}
})
InnerComponent
<aura:component >
<aura:attribute name="contact" type="Contact" />
<aura:attribute name="fieldName" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<ui:outputText aura:Id="outputTextId" />
</aura:component>
InnerComponentControllerJS
({
doInit : function(component, helper) {
var Contact = component.get('v.contact');
var FieldName = component.get('v.fieldName');
var outputText = component.find("outputTextId");
if (FieldName.indexOf(".") >= 0) {
var ParentSobject = Contact[FieldName.split(".")[0]];
if(ParentSobject != undefined){
outputText.set("v.value",ParentSobject[FieldName.split(".")[1]]);
}
}
else{
outputText.set("v.value",Contact[FieldName]);
}
}
})
Output