0

I guess I should also note that this is being done inside of a Salesforce LWC component. Let's say your response contains something like..

{
"color":"#FF0000",
"name":"Spectacular",
"label":"Glorious Labels",
"sort":"true",
"type":"link"
}

I'm looking for a solution that is kind of like the code below, but without the hard coding of the values to make it generic.

for (let i = 0; i < column.length; i++) {
    this.columnData[i] = {label:column[i]['label'], name: column[i]['name'],
    type: column[i]['type'], sortable: column[i]['sort'], color: column[i]['color']};
}

I have tried using Object.keys, Object.entries, Object.values and HasOwnProperty, but the results had issues and made them too difficult to pass around with the project I am working on (Job specific, NDA). I also don't want to have to convert it to a string value, parse the string and convert it back to JSON.

Note: I have also tried the obj[Object.keys(obj)[0]]; approach, it did not work as expected.

Any suggestions or examples would be extremely helpful. I have done a lot of research into this and have been testing ideas i've had for the past week and finally broke down to ask this amazing community.

Edited to give more context:

    import {LightningElement, track, wire, api} from 'lwc';
    import getData from '@salesforce/apex/AccountController.getRecords';
    import { NavigationMixin } from 'lightning/navigation';
    
        export default class AccountLwc extends LightningElement {
        @api recordId; 
        @api ObjectName;
        @api FieldSetName;
        @api WhereString;
        @api LinkFieldList; 
        @api ColorList; //= 'red|{1,2,3,4,5}|blue|yellow|purple|indigo|black|white|cyan|orange'; // a pipe delimited color list.
        @api sortable; 
        @track column; 
        @track row; 
        @track sortBy; 
        @track sortDirection; 
        columnData = {};
        rowData = {};
    
    @wire(getData,{recId: '$recordId', strObjectName: '$ObjectName', strFieldSetName: '$FieldSetName', strLinkFieldList: '$LinkFieldList',
            strColorList: '$ColorList', strSortable: '$sortable', strWhereString: '$WhereString'})
        wiredGetData({data}) {
            // if there is no data, exit from the function call for now.
            if (!data) return;
            // this allows for our data to be modifiable.
    
            let allData = JSON.parse(JSON.stringify(data));
            console.log(allData);
            this.BuildColumnsAndRows(allData);
        }
    
        BuildColumnsAndRows(data) {
            // grab all the data that is attached to the lstDataTableData key.
            let row = this.findAllByKey(data, 'lstDataTableData');
            // grab all the data that is attached to the lstDataTableColumns key.
            let column = this.findAllByKey(data, 'lstDataTableColumns');
    
            // loop through all the data and set our row data object to store all the results.
            for (let setter = 0; setter < row.length; setter++) {
                this.rowData[setter] = row[setter];
            }
    
            for (let setter = 0; setter < column.length; setter++) {
                this.columnData[setter] = {label:column[setter]['label'], fieldName: column[setter]['fieldName'],
                    type: column[setter]['type'], sortable: column[setter]['sortable'], color: column[setter]['color']};
            }
    
            this.row = Object.keys(this.rowData).map(key => this.rowData[key]);
    
            this.column = Object.keys(this.columnData).map(key => this.columnData[key]);
    
    /*      Object.keys(column).forEach( function (key) { console.log('foreach results: ' + JSON.stringify(column[key]) + ':' + JSON.stringify(row[key])); } );
                    foreach results: {
                    "color":"",
                    "fieldName":"Account__c",
                    "label":"Account",
                    "sortable":"true",
                    "type":"link"}:{
                    "Status":"New",
                    "Amount":0,
                    "Account_Manager__c":"Sprint 61/62",
                    "Account_Manager":{
                    "Name":"Sprint 61/62",
                    "Id":"0051100000BS0FsAAL"},
                    "Id":"a1F11000007OnX9EAK",
                    "Start_Date__c":"2021-06-09"
            }*/
            //this.row = Object.keys(this.rowData).map(key => this.rowData[key]);
            //let columns = Object.keys(this.columnData).map(key => this.columnData[key]);
    
            //console.log('column: ' + JSON.stringify(this.column));
            //this.column = Object.keys(columnData).map(key =>
                //(this.refineColumns('',columnData[key].label,columnData[key].fieldName,columnData[key].type, columnData[key].sortable, columnData[key].color)));
    
        }
   /**
     * Recursive function to go through deeply nested objects and retrieve data by their ID ('fieldName') / ('label')
     * @param obj the data source
     * @param keyToFind the key that you are recursively searching for.
     * @returns {[string, object]} returns the key and reduces the object to a map.
     */
    findAllByKey(obj, keyToFind) {
        return Object.entries(obj)
            .reduce((acc, [key, value]) => (key === keyToFind)
                ? acc.concat(value)
                : (typeof value === 'object')
                    ? acc.concat(this.findAllByKey(value, keyToFind))
                    : acc
                , [])
    }
        }

<template>
    <div style="height: 300px;">
        <lightning-datatable
                             key-field="Id"
                             data={row}
                             columns={column}
                             hide-checkbox-column
                             sorted-by={sortBy}
                             sorted-direction={sortDirection}
                             onsort={handleSortData}>
        </lightning-datatable>
    </div>
</template>

I have posted the relevant code from the LWC JS (with name changes to object and field names to try to conform to the NDA as commenters have asked for more information regarding the data structure and more context.)

Jesse Glover
  • 325
  • 3
  • 14

0 Answers0