0

I need to flatten my SObject data dynamically based on another list. fieldToDisplayList contains list of fields to display, which I want to flatten. Using below syntax I'm able to flatten the data but it's hard-coded, which I want to avoid:

return{
    ...row, 
    companyName: row.rec[fieldToDisplayList[0]], 
    companyId: row.rec[fieldToDisplayList[1]]
}

JS Code:

flatData = flatData.map((row, index)=>{
    var flattenSObjectData;
    for(var j = 0; j < fieldToDisplayList.length; j++) {
        flattenSObjectData = [];
        // this is not returning any value
        console.log('>>> fieldToDisplayList values... ', fieldToDisplayList[j]); 
    }
                                    
    // This works fine, instead of hardcoding values here want to do it using for 
    // loop, but in console log I'm not getting any value
    return{
        ...row, 
        companyName: row.rec[fieldToDisplayList[0]], 
        companyId: row.rec[fieldToDisplayList[1]]
    }
});
4
  • 1
    +fieldToDisplayList[j] tries to convert the contents to a number (because it follows ,, which makes it a separate parameter to console.log). I presume this isn't what you meant to do.
    – sfdcfox
    Commented Dec 9, 2020 at 14:36
  • Yes, that's mistake, but how do I iterate it to flatten Commented Dec 9, 2020 at 14:59
  • How do you know where companyName is supposed to come from? You can do this dynamically, but you need a way to map the values together.
    – sfdcfox
    Commented Dec 9, 2020 at 15:49
  • Well instead of CompanyName, I created an attribute based on a combination of object and it's field API name, to make it unique. Thanks for your help Commented Dec 9, 2020 at 16:53

1 Answer 1

0

Resolved the issue:

flatData = flatData.map((row, index)=>{
                                var flattenSObjectData = {};
                                for(var j =0; j < fieldToDisplayList.length; j++){
                                    let labelName = this.DefaultObject + fieldToDisplayList[j];
                                    flattenSObjectData[labelName] = row.rec[fieldToDisplayList[j]];
                                    //flattenSObjectData.push({companyName : row.rec[fieldToDisplayList[j]]});
                                    console.log('>>> fieldToDisplayList values... '+fieldToDisplayList[j]);
                                }
                                console.log('>>> flattenSObjectData... '+JSON.stringify(flattenSObjectData));
                                
                                //return{...row, Company__cName: row.rec[fieldToDisplayList[0]], Company__cId: row.rec[fieldToDisplayList[1]]}
                                return{...row, ...flattenSObjectData}
                            });

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .