To map them by Unique Id
for later use:
Map<String, Account> existingAccounts = new Map<String, Account>();
for (Account existingAccount : [
SELECT Unique__c FROM Account
WHERE Unique__c IN :allUniqueIds
]){
existingAccounts.put(existingAccount.Unique__c, existingAccount);
}
Then when iterating through you can retrieve them by that value.
String uniqueId = registration.account.Unique__c;
if (existingAccounts.containsKey(uniqueId))
registration.account.Id = existingAccounts.get(uniqueId).Id;
You can only have one value per key in a map. Calling Map.put(...)
on the same key will replace the existing value in the given key.
Try running the snippet below in a developer console to display this behavior.
Map<String, Boolean> mapAndValues = new Map<String, Boolean>();
// Assign multiple values to same key
mapAndValues.put('test', true);
mapAndValues.put('test', false);
System.debug(mapAndValues.get('test')); // will return false
An alternative option to using put
on the same key would be to use a list type as the value to the map.
Map<String, List<Boolean>> mapAndValues = new Map<String, List<Boolean>>();
// Assign empty list
mapAndValues.put('test', new List<Boolean>());
// Modify list reference from get
mapAndValues.get('test').add(true);
mapAndValues.get('test').add(false);
System.debug(mapAndValues.get('test')); // will return (true, false)
To iterate over the records in your list as specified in your question, you'll need to create a loop which acts on the list provided from calling get
on the key.
// First log id to be used to get other records
System.debug(logginglevel.INFO, 'PersonAccount DEBUG: MAP key = ' + id);
// Loop over list at specified key
for (ERP_Customer__c erp:acctErpMap.get(id))
{
// Log each record
System.debug(logginglevel.INFO, 'PersonAccount DEBUG: MAP value = ' + erp.Id);
}
To check if a key is in a map, you need to use the method containsKey(...)
, as opposed to the method contains
.
someMap.containsKey(someKey); // returns either true or false
Best Answer
Pretty much all browsers support the JavaScript method
Object.keys()
which takes in an object and returns an array of just its keys. So you could have a second attribute of typeString[]
and set it in the controller equal toObject.keys(theMapYouWantToIterate)
. A bit more troublesome though is the fact that you can't actually look up that index of the map in Aura binding notation (e.g{!v.myMap[key]}
doesn't work).So if you need to iterate and use both the name and values, you might alternatively want to pass it to the controller as a list of objects (i.e.
Map[]
) where each object has aname
and avalue
. If you have no choice but to start with a map in the controller, you can transform it to a list of objects something like this:var listOfObjects = Object.keys(myMap).map(function(key){return {name: key, value: myMap[key]} })
.