Access Fields of an Object Dynamically in Lightning

In this post, we will implement the functionality to access Fields of an Object dynamically in Lightning Component. Ideally, we can access the Field of an Object using {!v.objectName.fieldName}. For example, to access the name of Account, we can use {!v.account.Name}. But what if we don’t know the name of the Field we want to access? What if the name of a Field should be dynamic?

We can store the name of the Field in variable dynamically and then we should be able to access the value of that field. If the variable has value Name, then the Account Name should be displayed. If the variable has the value Phone, then the Account Phone should be displayed. Let’s hop into the implementation and see how can we achieve this?

Implementation

In this implementation, we will create a Lightning Component that will display a list of Accounts. We will access the column dynamically in Lightning Component.

First, create an Apex Class to return list of Accounts.

AccountUtility.apxc

public class AccountUtility {
	@AuraEnabled
    public static list<Account> fetchAccounts(){
        return [SELECT Name, AccountNumber, Phone, Website 
                FROM Account ORDER BY CreatedDate
                LIMIT 5];
    }
}

Create a Lightning Component to call this Apex method to fetch the list of Accounts from init handler.

AccountsController.js

({
    doInit : function(component, event, helper) {
        
        var columns = ['Name','AccountNumber','Website'];
        component.set('v.columns', columns);
        
	let action = component.get("c.fetchAccounts");
        action.setCallback(this, function(response) {
            let state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.lstAccount", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
    }
})

The columns variable stores the list of columns to display and lstAccount stores the list of Accounts.

For the simplicity of this demonstration, we will create an HTML Table in Lightning Component. To display the list of Accounts, we need to first loop through columns to create Table Header Row inside table tag like below:

<tr>
    <aura:iteration items="{!v.columns}" var="col">
        <th>{!col}</th>
    </aura:iteration>
</tr>

This will create a Table Header Row with columns Name, AccountNumber, and Website. To display the Rows of Account records, we have to loop through lstAccount. But to access the Fields of each record, we must know the name of Field to access like below:

<aura:iteration items="{!v.lstAccount}" var="acc">
    <tr>
        <td>{!acc.Name}</td>
        <td>{!acc.AccountNumber}</td>
        <td>{!acc.Website}</td>
    </tr>
</aura:iteration>

Here, we are displaying Name using acc.Name, and the same for the other two fields as well. Later, if want to change the column to display, or add/remove columns, we need to make changes in the Component as well as in the JS Controller.

Access Fields of an Object Dynamically in Lightning

There is a way to make it dynamic such that, if we want to add/remove the columns, we just need to make a change in columns variable in JS Controller. And our code will take care of displaying the Table and its columns dynamically.

To achieve this, we first need to create a simple Lightning Component. We will call it Cell. It looks like below:

Cell.cmp

<aura:component >
    <aura:attribute name="acc" type="Account" />
    <aura:attribute name="fieldName" type="String" />
    <aura:attribute name="value" type="String" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    {!v.value}
</aura:component>

We will accept the Account record and name of the field in acc and fieldName respectively. And in the doInit method, we will use the Javascript syntax acc[fieldName] to display the value of that fieldName dynamically.

CellController.js

({
    doInit : function(component, event, helper) {
        var acc = component.get('v.acc');
        var fieldName = component.get('v.fieldName');
        component.set('v.value',acc[fieldName]);
    }
})

Finally, we just need to update our code to display the Table Rows for the list of Records using Cell Component like below:

<aura:iteration items="{!v.lstAccount}" var="acc">
    <tr>
        <aura:iteration items="{!v.columns}" var="col">
            <td><c:Cell acc="{!acc}" fieldName="{!col}"/></td>
	</aura:iteration>
    </tr>
</aura:iteration>

Here, we are first iterating through the list of accounts lstAccount. Inside it, we will iterate through the lstColumns to display the Child Component Cell. Pass current Account record and current column to Cell Component which will display the value for it dynamically.

This is how our complete Accounts component looks like:

Accounts.cmp

<aura:component implements="flexipage:availableForAllPageTypes" controller="AccountUtility">
    <aura:attribute name="lstAccount" type="List" />
    <aura:attribute name="columns" type="List" />
	<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <lightning:card title="Access Fields of an Object Dynamically">
    	<div class="slds-p-around_small">
            <table>
            	<tr>
                    <aura:iteration items="{!v.columns}" var="col">
                        <th>{!col}</th>
                    </aura:iteration>
                </tr>
                <aura:iteration items="{!v.lstAccount}" var="acc">
                    <tr>
                        <aura:iteration items="{!v.columns}" var="col">
                            <td><c:Cell acc="{!acc}" fieldName="{!col}"/></td>
                    </aura:iteration>
                    </tr>
                </aura:iteration>
            </table>
        </div>
    </lightning:card>
    
</aura:component>

Output

Access Fields of an Object Dynamically in Lightning
Access Fields of an Object Dynamically in Lightning

This is how we can Access Fields of an Object Dynamically in Lightning Component.

If you want to add/remove the column or update the column, just update it in the columns list in JS Controller and you are good to go. You can even use the FieldSet to save the list of Columns and fetch it in the Lightning so that you don’t have to deploy code to add/remove the columns. Just update and deploy the FieldSet.

I have covered this in Dynamic List Component in Lightning implementation, where a single Lightning Component can be used to display Dynamic Table with Customizable Fields for any Object without changing a single line of code. I highly recommend to check it.

If you don’t want to miss new implementations, please Subscribe here.

See you in the next implementation.