Salesforce script to fetch object which contains fields using fields API

When we work with objects in salesforce, sometimes we need a few things dynamically like a list of object names that contain field with a given API name of the field. So, here is a script that gives us all the objects which contain those fields.

String fieldAPI = ‘fieldAPI__c’; // API name of field to be searched List sObjectList = new List(); //fetching objects which will be used to get field names for(Schema.SObjectType eachShema : Schema.getGlobalDescribe().Values()){ String objectName = eachShema.getDescribe().getName(); // Exclude all the unwanted sObjects e.g. History, Share etc.. if(!objectName.containsignorecase(‘history’) && !objectName.containsignorecase(‘tag’)&& !objectName.containsignorecase(‘share’) && !objectName.containsignorecase(‘feed’)) { sObjectList.add(objectName); } } //Loop over object list to compare field names with desired field name for(String sobject_type : SobjectList){ Map<String, Schema.SObjectType> global_describe = Schema.getGlobalDescribe(); Map<String, Schema.SObjectField> object_fields_map = global_describe.get(sobject_type).getDescribe().fields.getMap(); for(String key : object_fields_map.keyset()){ if(key.equalsIgnoreCase(fieldAPI)){ // ………….. System.debug(sobject_type); System.debug(key); } } }