Reputation: 143
All
I am just unable to get around my head with the issue, so posting is here for some help.
I have a object that contains the following
and for the same product Id there are multiple enteries.Example:
ProductId-----CustomFieldName---CustomFieldValue
111111111-----firstName---------TestUser
111111111-----lastName----------TestFUser
111111111-----phoneNumber-------1243
222111111-----firstName---------AnotherTestUser
222111111-----phoneNumber-------5243
I want to normalize the data, in another object:
ProductId-----firstName---------lastName------phoneNumber
111111111-----TestUser----------TestFUser-----1243
222111111-----AnotherTestUser---NULL----------5243
I tried normalizing it with Maps in for loop, but the code did not work for me. I cannot paste the code but here is the high level
Define a Map
//mapAttributes has the non-normalized data
Map<Id, Map<String, String>> mapme = new Map<Id, Map<String, String>>();
Map<String, String> tryme;
for (String a: mapAttributes.keySet())
{
tryme = new Map<String, String>();
tryme.put(mapAttributes.get(a).CustomFieldName, mapAttributes.get(a).CustomFieldValue);
mapme.put(mapAttributes.get(a).Id, tryme);
}
The outcome of the code is that the "tryme" looks like a reference and all the products have the same first,lastname and phone number...
I am not sure how can I normalize the data. The solution was so easy in my head, but in practicality is not working.
Any other approach of solving is appreciated as well.
I want to solve it in Salesforce Apex, can someone please help
Upvotes: 0
Views: 207
Reputation: 19612
A lot depends how your source data structure looks like.
List<String> lines = new List<String>{
'111111111-----firstName---------TestUser',
'111111111-----lastName----------TestFUser',
'111111111-----phoneNumber-------1243',
'222111111-----firstName---------AnotherTestUser',
'222111111-----phoneNumber-------5243'
};
Map<String, Map<String, String>> collated = new Map<String, Map<String, String>>();
for(String l : lines){
List<String> columns = l.split('\\-+'); // split by "-", treat multiple as one
String key = columns[0];
if(collated.containsKey(key)){
collated.get(key).put(columns[1], columns[2]);
} else {
collated.put(key, new Map<String, String>{columns[1] => columns[2]});
}
}
System.debug(JSON.serializePretty(collated));
gives
{
"222111111" : {
"phoneNumber" : "5243",
"firstName" : "AnotherTestUser"
},
"111111111" : {
"phoneNumber" : "1243",
"lastName" : "TestFUser",
"firstName" : "TestUser"
}
}
Upvotes: 1