InfoPath Code - Loop through items in a secondary data source from a SharePoint List
The article linked below demonstrates using JScript or VBScript, how to loop through items in a secondary data source until one is found which either contains a specific value, or has a specific value for a known attribute. InfoPath - Update Repeating Elements in a Secondary Data Source