[SalesForce] Problem passing a list of sObjects from apex to JavaScript

In apex I retrieve a list of sObjects and store them in a list. So it looks like this: public static List<sObject> listOfSobjects {get;set;}

And then I query for this sobject from the db:

listOfSobjects = [SELECT Id, Value1, Value2, (SELECT Id FROM sObject2) FROM Sobject WHERE Status__c != 'Rejected'];

So then I try to access this in JavaScript and assign it to a JavaScript object but I get an error. Even console.log gives me an error console.log({!listOfSobjects});

The error looks like this: Uncaught ReferenceError: a0H3B000000EWilUAG is not defined

Also in sources of the inspector that line of code looks like this console.log([a0H3B000000EWilUAG]);

Any ideas why I am getting an error in the console.log and also how to assign this list to a javascript object? Thank you.

Best Answer

Arthlete, If you want to use apex data type in javascript then that could be achieved by serializing the data that you want in javascript and then deserializing in javascript like as below. In Apex:

public String serializedList {get;set;}

serializedList = JSON.serialize(listOfSobjects );

Now in javascript you need to use below code:

var data = JSON.parse('{!serializedList }');

Now from data you would be able to access data you want.

Hope this helps.