[SalesForce] Display a list with data from more than one Object

I have a lightning component shown on account objects, which displays related accounts.

The CMP is basically something like this:

<aura:iteration items="{!v.accounts}" var="account">
    {!account.Name}
</aura:iteration>

The items in v.accounts are filled by a SOQL query in the apex controller, basically querying a custom object that binds two accounts together by storing their Ids as left and right column.

Now I want to display something from the custom object along with the account name.

How would I go about that?

Best Answer

What you are looking for is to merge two list into a third one. I won't post step-by-step code because your lack of details makes it difficult for me to go in relevant detail. However, I can post a generic approach that shouldn't be hard for you to translate into your reality.

My example assumes that your objects will have either properties with the same name or that you will combine attributes from different names into a common one.

Here it goes. In the component, add a generic list and reset your iteration to it

<aura:attribute name="myList" type="Object" />

<aura:iteration items="{!v.myList}" var="myRec">
    {!myRec.Id}
    {!myRec.Name}
    {!myRec.Prop2__c}
    {!myRec.Prop3__c}
</aura:iteration>

In your helper/controller, you will first get your records (I assume you know how to do that) an then combine them into this new object like so

var myList = [];
var accounts = component.get('v.accounts');
var otherRecs = component.get('v.otherRecs');

//a for loop is faster than a .foreach
for (var i = 0; i < accounts.length; i++) {
  var rec = {};

  rec.Id = accounts[i].Id;
  rec.Name = accounts[i].Name;
  rec.Prop2__c = accounts[i].SomeProp2__c;
  rec.Prop3__c = accounts[i].SomeProp3__c;

  myList.push(rec);
}

for (var i = 0; i < otherRecs.length; i++) {
  var rec = {};

  rec.Id = otherRecs[i].Id;
  rec.Name = otherRecs[i].Name;
  rec.Prop2__c = otherRecs[i].SomeProp2__c;
  rec.Prop3__c = otherRecs[i].SomeProp3__c;

  myList.push(rec);
}

component.set('v.myList', myList);

Voila!

PS: Obviously, replace the variable names with real ones. On the left, the properties of your rec records should be identical in both lists. On the right, however, you can use any property on the accounts and otherRecs. My advice, however, is that you use properties of the same types (numbers, dates, etc) for the same rec property, to avoid issues when formatting (unless you want to treat them all as strings)

PPS: Other suggestions on this topic suggest to do the same thing it in Apex. If possible, that is desired since it'll save you a trip to the db... but it may make your code harder to maintain. Or, perhaps, you already have all the data and need to aggregate on the front end. If the latter, then I'd do it in JS.

Related Topic