Best way to loop through two objects

  • 3
    Welcome to Salesforce Stack Exchange (SFSE). Thank you for the details so far, but this site exists to help, not provide full implementation. (Please note in the Help Center section What topics can I ask about here? that it states, "Questions that ask for the community to write code or provide step-by-step instructions for implementation...are likely to be closed.") So please edit your question to include what you have tried & how it is not working (e.g., exact errors, issues).
    – Moonpie
    Sep 11, 2021 at 19:54
  • 2
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Sep 12, 2021 at 1:20

1 Answer 1


There are two parts to your question. First making a dynamic query based on the results that you have fetched from custom metadata.

Assuming your provided metadata example.

Id      Field 
id-123  field1__c
id-456  field2__c

The dynamic query can be created in the following manner.

//query the metadata
List<CaseField_mdt> metalist = [SELECT Id, Field FROM CaseField_mdt];

/*Now since you want the final results in key-value format where your key is 
  metadata field, so you create a map, to keep key-value mapping. This will 
  help in creating the query as well as generating the results in required 

Map<String, String> fmap = new Map<String, String>();
for(CaseField_mdt m : metalist) {
  fmap.put(m.Field, m.Id);

Now In order to create your dynamic query on Case, you can use the map keys, to form a string, and query those required fields.

String query_str = 'SELECT' + String.join(new List<String>(fmap.keySet()), ', ') + ' FROM Case';

//execute your dynamic query
List<Case> cases = database.query(query_str);

//Create Your final result Map in required format
Map<String, sObject> result = new Map<String, sObject>();
for(Case c : cases) {
 for(String key : fmap.KeySet()) {
  if(c.get(key) != null) // field exists in case
    result.put(fmap.get(key) , c.get(key)); // {id-123: case1 }

System.debug('Result : ' + result); // This map will print your required format results.
  • 1
    A word of warning: the result map cannot be a map of SObjects; it needs to be an array of maps of string (the key, not field name) to field value (so just Object) and this should also consider (object and field level) security, which it does not.
    – Phil W
    Sep 12, 2021 at 7:20
  • Thanks, @Rohit Yadav, your code works for me.
    – Anjana
    Sep 14, 2021 at 17:05

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