Friday 24 November 2023

How to check the Column Name of object using For Loop

 

Sometimes in code, we need to check the column name is match with any string then a developer stuck on this. Sample code of this kind of problem statement is that

 

List<String> liColName = new List<String>();

boolean IsHide = false;

liColName.add('Column 1');

liColName.add('Column 2');

liColName.add('Phone');

 

Account acc = [select Id,Name,Phone from Account LIMIT 1];

Map<String, Object> fieldsToValue = acc.getPopulatedFieldsAsMap();

for(string str:liColName)

{

 

    for (String fieldName : fieldsToValue.keySet()){

        if(fieldName == str)

         System.debug('field name is ' + fieldName + ', value is ' + fieldsToValue.get(fieldName));

              

    }

}

 

In the Above code, getPopulatedFieldAsMap() returns the Map in which it returns the column name in Key and its value in Value of the Map


No comments:

Post a Comment