0

I have a map in apex class as a getter setter and currently accessing in the javascript of the visualforce page. But when i try to traverse a map, it is not displaying the values correctly, instead of each word, it is displaying the letters. Any help? Code :

function test() {
  //This is how the map stored in apex controller
  var buttonMap = {apple=1,banana=2,Grapes=4}; 
  for(var key in buttonMap) {
     console.log(buttonMap[key]); //Which displays values as a p p l e b = 1 b a 
  }

}
4
  • 2
    How did button map get in such a state? That's not even legal JavaScript code.
    – sfdcfox
    Jun 19 '18 at 17:55
  • Actually apex class returning the map in that format. I have below map in apex controller for(LiveChatButton chatButton:[SELECT DeveloperName FROM LiveChatButton WHERE DeveloperName =:buttonNamesSet LIMIT :Limits.getLimitQueryRows() - Limits.getQueryRows()] ) { buttonNameMap.put(chatButton.DeveloperName,chatButton.Id); } And i am trying to access the map in the javascript as below var buttonIds = {}; buttonIds = '{!buttonNameMap}'; Jun 19 '18 at 18:05
  • when i did console.log for buttonIds map was below format (Removed actual ids and data for security purpose but it will be button name,buttonid) {a=buttonId1, b=buttonid2, C=buttonId3} Jun 19 '18 at 18:10
  • 1
    can you share your apex controller?
    – glls
    Jun 19 '18 at 22:52
0

Apex Code's default serialization won't work for JavaScript. You need to convert it to JSON:

public String getButtonNameMap() {
  Map<String, Id> buttonNameMap = new Map<String, Id>();
  for(LiveChatButton chatButton:[SELECT DeveloperName FROM LiveChatButton WHERE DeveloperName =:buttonNamesSet LIMIT :Limits.getLimitQueryRows() - Limits.getQueryRows()] ) {
    buttonNameMap.put(chatButton.DeveloperName,chatButton.Id); 
   }
   return JSON.serialize(buttonNameMap);
}

And change your Visualforce slightly:

var buttonIds = {!buttonNameMap};
2
  • now the button map is somewhat OK It is rendering as ["buttonName":"buttonId","buttonName2":"buttonId2"]. But when try to loop through this map for(var key in buttonId) { console.log(buttonId[key]); } This is giving me same result , something like this [ b u t t o n 1 Jun 20 '18 at 6:22
  • Finally i made it work @sfdcfox. I followed below link and it is working now. Thanks for your help. salesforce.stackexchange.com/questions/69871/… Jun 20 '18 at 7:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.