0

I have a datatable in which I want to display the data in a certain way, namely: I have an Exchange_Rate__c object that has certain currency rates as fields: USD__c, CAD__c, EUR__c, GBP__c, as well as a Date__c field that displays the date when the currency rates were loaded from the external API.

In the table, I need to get 3 columns: Currency, Exchange Rate, Date. In the Currency field, I need to display the name of all my object fields, in the Exchange Rate field , the rate of the corresponding currency, and in the Date field, the date.

And now I don't understand how I can do it...

I get data from the database using the apex method and add it to my component in the list as follows: {"Date__c":"2021-05-28","GBP__c":1,"CAD__c":1.714795,"EUR__c":1.164868,"USD__c":1.419765,"Id":"a005e000002zrh5AAA"}

//cmp

<aura:component controller="CurrencyExchangeController">
<aura:handler action="{!c.doInit}" name="init" value="{!this}"/>
<aura:attribute name="listRecordsExchangeRates" type="Exchange_Rate__c[]"/>
<aura:attribute name="columns" type="List"/>
<lightning:datatable     keyField="computedId"
                         columns="{!v.columns}"
                         data="{!v.listRecordsExchangeRates}"/>
</aura:component>

//js

({
    
    doInit : function(component, event, helper) {
    component.set('v.columns', [
        { label: "Currency", fieldName: "currency" },
        { label: "Exchange Rate", fieldName: "exchangeRate" },
        { label: "Date", fieldName: "exchangeDate" }
    ]);
    helper.getDataFromDB(component, helper);
    }
})

//helper

({
    
    getDataFromDB : function(component, helper){
        let action = component.get('c.getListExchangeRates');
            action.setCallback(this, function(response) {
        let state = response.getState();
            if (state === "SUCCESS") {
            /**JSON.stringify(returnValue) = [{"Date__c":"2021-05- 28","Base_Currency__c":"GBP","GBP__c":1,"CAD__c":1.714795,"EUR__c":1.164868,"USD__c":1.419765,"Id":"a005e000002zwmtAAA"},{"Date__c":"2021-05-29","Base_Currency__c":"GBP","GBP__c":1,"CAD__c":1.713786,"EUR__c":1.163787,"USD__c":1.41895,"Id":"a005e00000305KhAAI"}]*/
                let returnValue = response.getReturnValue();
                let currencies = ["GBP__c","CAD__c","EUR__c","USD__c"];
                let data = currencies.map(
                (currency) => returnValue.map((record) => ({
                computedId: `${currency}-${record.Id}`,
                currency: currency.replace('__c',''),
                exchangeRate: record[currency],
                exchangeDate: record.Date__c,
                Id
              }))
            ).flat();
            component.set("v.listRecordsExchangeRates", data);
            }
    });
    $A.enqueueAction(action);
}

I didn't get anything in the table...

enter image description here

1

Unless you want to do it server-side, which is certainly an option, you can write it as a relatively simple client-side action.

First, we have to compute the ID, because the record Id won't be unique in our case. We're going to have to change each record into several rows.

Example Table

That means we're going to change the markup to look like:

<lightning:datatable     keyField="computedId"
                         columns="{!v.columns}"
                         data="{!v.listRecordsExchangeRates}"/>

Next, we simply need to map the data as we like.

let returnValue = result.getReturnValue();
let currencies = ["GBP__c","CAD__c","EUR__c","USD__c"];
// For each currency
let data = currencies.map(
  // For each record
  (currency) => returnValue.map((record) => ({
    // Calculate a unique Id
    computedId: `${currency}-${record.Id}`,
    // Take off the __c at the end
    currency: currency.replace('__c',''),
    // Get the appropriate exchange rate (e.g. GBP__c)
    exchangeRate: record[currency],
    // And the exchange date
    exchangeDate: record.Date__c,
    // And the Id, if you need to know it
    recordId: record.Id
  }))
// We now have an Array of Arrays, so we flatten with flat()
).flat();
component.set("v.listRecordsExchangeRates", data);

I wrote this as a LWC to give you an idea of what it would look like, and I've included the basic Aura you need above, it's just a matter of plugging this into the callback function (I presumed the callback is function(result) {...}).

4
  • I edited my code based on your answer, but I probably missed something. My table is empty... May 30 at 12:42
  • @uniqueuser That's weird. Updated the example using the literal data you provided, it still works. I did make a small change in my code, but it's probably immaterial to your situation. Try using the new edit, though, maybe it's a "undefined variable" error. You may want to try debugging using the F12 debugger tools to see what's wrong. Also, try logging data to the console to see what it looks like.
    – sfdcfox
    May 30 at 13:48
  • Wow! Now it works! Apparently this is your change affected: recordId: record.Id. Thank you so much! May 30 at 16:12
  • @uniqueuser Glad to help!
    – sfdcfox
    May 30 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.