On a recent project I had to send a collection of objects from JavaScript to an embedded Flash application. Each object was an associative array containing properties options for different elements in the Flash app. It turned out fairly cumbersome to actually do so! First, let’s review the ways that an associative array can be created in JavaScript:
1) An object literal
var arr = {name: "edge-color", group: "edges"};
2) An object
var arr = new Object(); arr.name = "edge-color" arr.group = "edges";
3) An array literal
var arr = ["name": "edge-color", "group" : "edges"];
4) An array object
var arr = new Array(); arr.name = "edge-color" arr.group = "edges";
All of these are acceptable means of creating an associative array. Next, we need to send this information to the Flash object using the ActionScript ExternalInterface class. This is where our trouble starts. If you use either of the options 3 and 4, this will NOT WORK! Array is a special class that has strange underpinnings. Only Object will be translated, and the most reliable way to do that is by converting to JSON. First, if you are using a modern browser the function JSON.stringify(Object) should be available to you without any special include on JavaScript.
On the ActionScript side, decoding JSON is equally straightforward:
var object:Object = JSON.decode(s);
I’ll leave it up to the reader to figure everything else out…
