2

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?

1 Answer 1

1

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);
6
  • Thanks for the quick response @Uwe Heim. So, first I need to convert accountWrapperList in JSON format right .. ? Apr 5, 2015 at 12:50
  • My assumption: it's already JSON. If not use in apex JSON.serialize(yourList) and return that as accountWrapperList (change type to string) - but first try it as-it-is now and test if it's auto coverted already.
    – Uwe Heim
    Apr 5, 2015 at 12:53
  • What ever it is - just let me know and I'll update my answer.
    – Uwe Heim
    Apr 5, 2015 at 12:58
  • It wasn't a JSON string already. I converted the list into JSON first and then parsed it as you said. It's working fine. Thanks a ton Uwe. Apr 5, 2015 at 13:43
  • Can you elaborate when do we need to parse a JSON string? I mean, what makes you decide that you need to parse the string to get the requirement done. . ? Apr 5, 2015 at 20:26

You must log in to answer this question.

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