LWC – Passing Array of Objects to Apex Class

apexjavascriptlightning-web-components

I have array of object which contains two different objects data e.g Secction__c and Question__c

@track addSectionRecord = [
    {
      id: '',
      section: '',
      sort: '',
      Question: [{
        subQues: '',
        sort: ''
      }]

    }
  ];

Now i want to pass this array of object to apex method like that
apexMethod({apexList:this.addSectionRecord}) from JavaScript. Firstly how to declared the list apexList in apex.Secondly how to iterate the list in apex to get data for these two obejects.

Best Answer

apexList could be defined as follows:

public class Section {
  @AuraEnabled public String id { get; set; }
  @AuraEnabled public String sortOrder { get; set; }
  @AuraEnabled public question Question { get; set; }
}
public class Question {
  @AuraEnabled public String subQues { get; set; }
  @AuraEnabled public String sortOrder { get; set; }
}
@AuraEnabled public static void apexMethod(Section[] apexList) {

Actually processing this uses a nested loop:

for(Section section: apexList) {
  for(Question question: section.Question) {
    // Do something here with section and question
  }
}

However, please note that sort is an Apex reserved keyword. The above code renames sort to sortOrder to avoid compile errors. If you do not want to refactor the client code, you can instead use a Map/List:

@AuraEnabled public static void apexMethod(List<Map<String, Object>> apexList) {
  for(Map<String, Object> section: apexList) {
    String sectionId = (String)section.get('id');
    String sectionSortOrder = (String)section.get('sort');
    for(Map<String, Object> question: (List<Map<String, Object>>)section.get('Question')) {
      String questionId = (String)question.get('id');
      String questionSortOrder = (String)question.get('sort');
      // Do something with section and question data
    }
  }
}

However, this code has a caveat that some people have had trouble with automatic serialization, so you might end up having to convert this to a JSON string (at which point, you'll need to modify client code anyways, so you should probably fix it to use the first version I've mentioned here anyways).

apexMethod({apexList:JSON.Stringify(this.addSectionRecord)}) 

...

@AuraEnabled public static void apexMethod(String apexList) {
  List<Object> values = (List<Object>)JSON.deserializeUntyped(apexList);
  for(Object sectionObject: values) {
    Map<String, Object> sectionData = (Map<String, Object>)sectionObject;
    String sectionId = (String)sectionData.get('id');
    String sectionSort = (String)sectionData.get('sort');
    for(Object questionObject: (List<Object>)sectionData.get('Question')) {
      Map<String, Object> questionData = (Map<String, Object>)questionObject;
      String subQues = (String)questionData.get('subQues');
      String questionSort = (String)questionData.get('sort');
      // Do stuff here
    }
  }
}