Apex Aide apexaide

Salesforce Lightning DataTable Query Flattener

iwritecrappycode.wordpress.com· ·Intermediate ·Developer ·3 min read
Summary

The content demonstrates how to flatten nested SOQL query results for use in the Salesforce Lightning Datatable component, which does not natively support nested arrays or complex objects. It provides Apex and Lightning controller code patterns to fetch Contact records and related data, then flatten parent-child structures for easy display. This approach helps Salesforce developers avoid building complex wrapper classes while still showing parent and child fields in a simple Lightning datatable. Teams can adopt this flattening technique to efficiently display nested relationship data in Lightning components.

Takeaways
  • Flatten SOQL nested query results to make data compatible with Lightning datatable.
  • Use recursive flattenObject function to convert nested objects into single-level key-value pairs.
  • Handle child object arrays by mapping each item with indexed property names.
  • Leverage Apex controller to return queried data including parent and child relationships.
  • Set Lightning datatable columns to match flattened property names for display.

So I was doing some playing around with the Salesforce Lightning Datatable component and while it does make displaying query data very easy, it isn’t super robust when it comes to handling parent and child records. Just to make life easier in the future I thought it might be nice to make a function which could take a query returned by a controller and ‘flatten’ it so that all the data was available to the data table since it cannot access nested arrays or objects. Of course the table itself doesn’t have a way to iterate over nested rows so the child array flatted function is not quite as useful (unless say you wanted to show a contacts most recent case or something). Anyway, hopefully this will save you some time from having to write wrapper classes or having to skip using the data table if you have parent or child nested data.

ApexLightningSalesforce