[SalesForce] Parsing array of object Json in LWC

I'm getting a JSON response as below

Enroll Status –>{"data":[{"Id":"a082w000000YUH5AAO","EnrolStatus__c":"Submitted"}]}

How to read the object value in the response.( Always this will be a single object in an array);

@track enrollStatus;
 @wire(getEnrollmentStatus, {EnrollmentId: "$recordId" })
getenrollStatus(enrollstatus){
console.log('Enroll Status  -->' + JSON.stringify(enrollstatus))
 }



 public static List<Enrollment__c> getEnrollmentStatus(Id EnrollmentId) {          
    system.debug('ENROL ' + EnrollmentId);              
    return   [select  Id, EnrolStatus__c from Enrollment__c WHERE Id=:EnrollmentId];                
    }

Best Answer

You can parse it as below. As you are sure, the result always will have a single value in the array inside response, You can get the JavaScript array elements using index.

this.parsedValue = JSON.parse(enrollstatus);
console.log('this.parsedValue ' + this.parsedValue.data[0]);
console.log('this.parsedValue ' + this.parsedValue.data[0].Id);
console.log('this.parsedValue ' + this.parsedValue.data[0].EnrolStatus__c);

enter image description here

Parse the data with JSON.parse(), and the data becomes a JavaScript object.

Related Topic