Data Tables in LWC gets painful to work with when you want to display the data  from related objets into a single data table.

Data tables in LWC showing data from related objects

The bottle neck that we face here is when we get the data back, that’s going to be in nested json format.

There are a couple of things on which we need to work on to get the Data Tables in LWC to work as expected.

  • The response that we get from Apex method should resemble the json we declared for the columns in data table. Something like this ..
const columns = [
    { label: 'Label', fieldName: 'Name' },
    { label: 'Website', fieldName: 'LeadSource' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    { label: 'Account Name', fieldName: 'Account.Name'},
    { label: 'Account Industry', fieldName: 'Account.Industry'}
    
];
  • The response we get will be similar to the format shown below and we need to flatten it to resemble the json declared for the columns. So the below json response should be flattened to ..
{
    "Id": "0032v00002lLzgQAAS",
    "Name": "Rose Rose",
    "Phone": "(512) 757-6000",
    "LeadSource": "Trade Show",
    "AccountId": "0012v00002M0O2CAAV",
    "Account": {
      "Name": "Edge Communications",
      "Industry": "Electronics",
      "Id": "0012v00002M0O2CAAV"
    }
}

something like this ..

{
    "Id": "0032v00002lLzgQAAS",
    "Name": "Rose Rose",
    "Phone": "(512) 757-6000",
    "LeadSource": "Trade Show",
    "AccountId": "0012v00002M0O2CAAV",
    "Account.Name": "Edge Communications",
    "Account.Industry": "Electronics",
    "Account.Id": "0012v00002M0O2CAAV"     
}

Okay! Let's get started.

This is how my template file is going to look like.

<template>
    <div style="height: 500px;">
        <lightning-datatable
                key-field="id"
                data={allContacts}
                columns={columns}>
        </lightning-datatable>
    </div>    
</template>

Then comes the js file.

It's not that we can only show data from two related objects. We can also show data from multiple objects which are in relationship, as long as the flattened json response is resembling the json we used in declaring the columns.

In case you are not a blog person and interested in salesforce tutorials (video) then check this out.