0

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.

1 Answer 1

4

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.

3
  • 1
    Basically this method gives you JSON representation of your data in String format. After getting all listOfSobjects you need to call this method and assign returned string in another string type of variable which you could use in vf page. Apr 4, 2016 at 16:39
  • Thank you so much, this worked! Why do I need to serialize it. Why will it not work without converting it to a json string? @KiranMachhewar
    – Arthlete
    Apr 4, 2016 at 16:45
  • 1
    In that way it will call it's toString version which does not give output in json string. Apr 4, 2016 at 16:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .