Creating Javascript arrays on the fly

The need to build a Javascript array is pretty non-existent since many scripting engines (or at least the ones I use) can natively return objects in JSON.  However, if for some reason you cannot get your data back as JSON I whipped up a quick example of how it can be done.  This is more a note for myself, but maybe someone will find it useful.

First we take the data that we already have available in ColdFusion and build the Javascript array.  In our Javascript we create a new variable and set it to the value ColdFusion has built for us.  Below is the code:

 dataString = "";
 // Build an array of people to play with
 people = arrayNew(1);
 people[1].name = "Jim";
 people[1].hairColor = "Brown";
 people[1].eyeColor = "Brown";
 people[2].name = "John";
 people[2].hairColor = "Black";
 people[2].eyeColor = "Blue";
 people[3].name = "Jane";
 people[3].hairColor = "Blonde";
 people[3].eyeColor = "Green";
 // The "important" stuff (tm)
 jsArray = "[";
 for(y = 1; y lte 3; y = y + 1){
  dataString = listAppend(dataString, "{ name: '#people[y].name#', hairColor: '#people[y].hairColor#', eyeColor: '#people[y].eyeColor#' }");
 jsArray = jsArray & dataString;
 jsArray = jsArray & "]";   
<script type="text/javascript">
 var peopleArray = #jsArray#;
 function dumpArray( obj ){
  for(var i = 0; i < obj.length; i++){
   for(j in obj[i]){
    document.write('<strong>' + j + ':</strong> ' + obj[i][j] + '<br />');
   document.write('<br />');

About Robert Zehnder

Web application developer specializing in ColdFusion/Railo and Open Source development.

Posted on March 1, 2010, in Javascript. Bookmark the permalink. 7 Comments.

  1. Couldn’t you also do:

    var #toScript(thisString, “jsVar”)#;<

  2. Couldn’t you also do:

    var #toScript(people, “peopleArray”)#;

  3. Yes, that is correct. Unfortunately the toScript() function was released in CFMX7. At work we are still running an earlier ACF version so I had to roll my own solution.

  4. You can also use to convert any native CF object to JS. This has been around forever.

  5. Crud, my comment isn’t showing up the way I typed it:

    You can also CFWDDX use to convert any native CF object to JS. This has been around forever.

  6. very cool & good tip, thank you very much for sharing.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: