Tutorial :Javascript is passing an Array of Objects instead of an Array of Arrays



Question:

I'm passing a Javascript Array() to Flash via FlashVars but Flash complains. Can you guys point me what am I doing wrong here?

javascript code

// array with the user defined cities  var usercities = new Array(       {'nome':"London", 'lat':51.5002, 'long':-0.1262 },      {'nome':"NYC", 'lat':51.5002, 'long':-0.1262 }   );    flashvars.newcities = usercities;  

flash code

// this array is pre-populated so if the users doesn't enter data this is shown  var cities:Array = new Array(      { nome:"London", lat:51.5002, long:-0.1262 },      { nome:"NYC", lat:40.7144, long:-74.0060 }  );    // gets FlashVars  var newcities:Object = LoaderInfo(this.root.loaderInfo).parameters.newcities;  if(newcities != null) {      cities = newcities;  };  

Doesn't work. I need to have the cities array on the Flash Side exactly as it is. On the Javascript side all code can change.

Thank you for your help.


Solution:1

JavaScript does not have associative arrays like other languages. In order to have named indexes, you have to use an object. An array that is assigned a value with a named index will be converted to an object.

In order to do this, you may need to change your Flash code. As meder said, serializing your array is your best bet. I'd suggest a JSON encode in the JavaScript and a decode in the Flash.


Solution:2

Well you can just manually make them arrays. Something like this:

var usercities = [];  usercities[0] = [];  usercities[0]["nome"] = "London";  usercities[0]["lat"] = 51.5002  usercities[0]["long"] = -0.1262  usercities[1] = [];  usercities[1]["nome"] = "NYC";  usercities[1]["lat"] = 51.5002  usercities[1]["long"] = -0.1262  

Though I think it is all the same but flash may be seeing it differently.


Solution:3

Ended up passing the values as this:

javascript

var cities = new Array(       Array("London", 51.5002, -0.1262),      Array("NYC", 40.7144, -74.0060),  );  

That flash gets as a pure string.

"London",51.5002,-0.1262,"NYC",40.7144,-74.0060  

I then exploded the string and converted to Array. It's a bit dirty but in the end works. As long as the Array always has 3 items per row and no item has a comma.

Hope this may help someone.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »