function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shiva Prasad Achukatla 22Shiva Prasad Achukatla 22 

loop through apex map in javascript

Hi, 

I want to loop through apex map in Javascript. 

My map is like below 
Map<string,list<wrapperObject>> Map_Of_AnswerGroup_childQuestionsGroup = new Map<string,list<warpperObject>>(); 
public String Map_Of_AnswerGroup_childQuestionsGroup_JSON {get;set;}

consrtuctor(){
     if(!this.Map_Of_AnswerGroup_childQuestionsGroup.isEmpty())
            {
                system.debug('debug at 534'+this.Map_Of_AnswerGroup_childQuestionsGroup);
                Map_Of_AnswerGroup_childQuestionsGroup_JSON = JSON.serialize(this.Map_Of_AnswerGroup_childQuestionsGroup.isEmpty());
            }
}

'Map_Of_AnswerGroup_childQuestionsGroup_JSON ' is retruning false after serlization. 

Could someone help me around this. 

The main purpose of this is to be able to loop through map elements in javascript and form dynamic mark up. 



 
LBKLBK
Here is an interesting piece of code I have found (and made some changes to make it work) to parse List in Javascript. I have tried it for map as well (Map<Id, Contact>), but it didn't work well, because the Ids get attached to JSON field names.

Here is the APEX code.
 
public class AccessMapJS {
    public Map<ID, Contact> resultsMap{get;set;} 
    public List<Contact> resultList {get; set;}
    public String JsonMap{get;set;} 

    public AccessMapJS(){
        resultsMap = new Map<ID, Contact>([SELECT Id, LastName FROM Contact limit 3]);
        resultList = [SELECT Id, LastName FROM Contact limit 3];
        //JsonMap=JSON.serialize(resultsMap);
        JsonMap=JSON.serialize(resultList); 
    }
}
And, the Javascript
 
<apex:page controller="AccessMapJS" >
<script>
var jsMap = '{!JsonMap}';
var jsonObjArr = JSON.parse(jsMap); //This will be a Javascript array that can be used to fetch Ids and Last Names.

// Create a Javascript Map
var map = new Object();

// Iterate throught the Array and Push into map Object
for(var count=0;count<jsonObjArr.length;count++)
{
   // JSON Object 
   var JSONObj = jsonObjArr[count];
   // Map key : Contact Id
   var ConId = jsonObjArr[count].Id;
   // Map Contact Id to JSON Object. Then you can use this object to get values  from Map. Storing Object in case you need more information than just Last Name. 
   map[ConId] = JSONObj;
}


for (var count =0; count < jsonObjArr.length; count++){
    alert(map[jsonObjArr[count].Id].LastName);
    alert(map[jsonObjArr[count].Id].Id);
}
</script>
</apex:page>

You are welcome to make it work for parsing Map object as well.

If you find it difficult, I suggest you convert your Map into a list, because it works like breeze with a List.

Hope this helps.