[SalesForce] Access sObject list variables in Javascript

Question:

I need to create list of sObjects in Javascript.

Let's assume accountWrapperList is a list of (Account + checkbox) defined in controller. You can access this list in your javascript if you use it like this:

var records = '{!accountWrapperList }';

However, this would be a string representation, not list representation.

To convert it into list, you will need to do something like this:

var records = new Array();
<apex:repeat value="{!accountWrapperList}" var="acc"> 
records.push('{!acc}');  
</apex:repeat> 
console.log(records);

You will see that records is now a list of sObjects.

Now coming to problem:
You can access this list like this – console.log(records[0]); — Since its a list.

BUT you cant access the list like this – returns "undefined".

console.log(records[0].check);

Despite the fact that "check" is a valid variable that can easily be seen in the console. Have tried many things, but its not working.
Can anyone plz suggest?

Best Answer

There is no need to use the apex:repeat. You can use the resulting records as string more directly.

What you have is a JSON serialized representation of your apex structure - that is a list of wrapper objects.

There is a javascript method called JSON.parse() to convert the string into an object - or an array of objects in your case:

var json = '{!accountWrapperList }';
var records = JSON.parse(json);

Now you should have something usable right here

console.log(records);

And also this should work as expected

console.log(records[0].check);