I am trying to fetch Map in my lightning js controller.

Apex Controller:

public static Map<CustomObject__c, custObj__c> getQuestions(){
    Map<CustomObject__c,custObj__c> quesOpMap = new Map<CustomObject__c, custObj__c>();
    List<custObj__c> obj = [SELECT Id,Name FROM custObj__c];
    for(CustomObject__c q : [SELECT Id,Name FROM CustomObject__c] )
        for(custObj__c opt : obj){
                   quesOpMap.put(q, opt);
    return quesOpMap;

JS Controller:

 var action = component.get("c.getQuestions");
    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
       var state = response.getState();
       if (state === "SUCCESS") {
            component.set("v.questions", response.getReturnValue());
        else {
            console.log("Failed with states: " + state);

on loading app I am getting error as 'Unable to parse JSON Response' and if check console log for response.getReturnValue(). this is undefined.

But If I replace Map<CustomObject__c, custObj__c> with any primitive type for e.g. - Map<Id,String> or Map<String,String>, js controller is working fine.

How to get values for custom objects in lightning controller?

  • The Apex code posted in the question is not correct as you are trying to put a string in the map against the key, whereas you have defined map of objects Dec 27 '17 at 13:31
  • Can you please check your debug logs Dec 27 '17 at 13:32
  • @maniaccoder I mistaklenly posted the wrong code. Edited it correctly Dec 28 '17 at 5:26

Your Map cannot be serialized to JSON, as the return values of @AuraEnabled controller methods are, because it uses an object as a key.

It's fine to return a map of a primitive to an object, like Map<String, CustomObject__c>, but you can't use a custom object as the Map key in this context.

  • so its not possible to set Map key as custom object? Dec 28 '17 at 5:27
  • 1
    @AnkurGupta Right. Keys must be Id or String. Coincidentally, it would make sense to just write something like quesOnMap.put(q.Id, opt).
    – sfdcfox
    Dec 28 '17 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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