Hello Friends, In this post we will see an example to converting queried sobject data in the map. One thing we have to keep in our mind is, it will only work single instance of sobject data not on the list of sobject data. so, let's get started,

Convert sobject data in the map in apex

To convert sobject data in the map salesforce has introduced a new sobject method named getPopulatedFieldsAsMap()

getPopulatedFieldsAsMap() - Returns a map of populated field names and their corresponding values. The map contains only the fields that have been populated in memory for the sObject instance.

Let see a code example to understand this method properly.

Example 1: On single object

 Account lstAccount=[SELECT Id,Name,Rating FROM Account limit 1];

 /*Populate sobject record into the map where key=Field_API and value=Field_Value*/
 Map<String, Object> accFieldMap = lstAccount.getPopulatedFieldsAsMap();
 for(String fName:accFieldMap.keyset()){
    System.debug('Field Name=='+fName+' Field Value=='+accFieldMap.get(fName));
 }
Output:


Example 2: On related object
 Contact c = [SELECT id, Contact.Firstname, Contact.Account.Name FROM Contact limit 1];
 Map<String, Object> fieldsToValue = c.getPopulatedFieldsAsMap();
 /*To get the fields on Account, get the Account object and call 
 getMapPopulatedFieldsAsMap() on that object.*/
 Account a = (Account)fieldsToValue.get('Account');
 Map<String, Object> accFieldMap = a.getPopulatedFieldsAsMap();
 for(String fName:accFieldMap.keyset()){
    System.debug('Field Name=='+fName+', Field Value=='+accFieldMap.get(fName));
 }
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.