[SalesForce] How to iterate over all the queried out fields of a single record

I need to iterate over all the fields that I query for a record and check all of those that are custom field checkboxes and see if any are true. The part that I'm not sure how to do is how to iterate over all of those fields after my SOQL query. So just to be more clear, regardless of any changes to the object (a new custom field gets added or an existing one gets removed) or even any changes to the SOQL in terms of adding new fields to the query or removing an existing field from the query. My code will still iterate over all of those that have been queried out.

Best Answer

You just need sObject.getPopulatedFieldsAsMap():

for(Object value: record.getPopulatedFieldsAsMap().values()) {
  if(value == true) {
    // We found a match
  }
}

If you need to know which field:

Map<String, Object> values = record.getPopulatedFieldsAsMap();
for(String fieldName: values.keySet()) {
  if(values.get(fieldName) == true) {
    // We found a match
  }
}

Note that only checkboxes can return true/false (including formula fields), so there's no need for a describe call.