views:

69

answers:

2

Hi!

Is there a way to return a new version of an array/hash that does not contain all the methods/functions that prototype extends the array object with?

Example:

var myArray = $A();

myArray['test'] = '1';

myArray['test2'] = '2';

var myVariableToPassToAjax = myArray;

If I debug myVariableToPassToAjax it looks like this:

Array
(

  [test] => 1

  [test2] => 2

  [each] => function each(iterator, context) {
    ..........
    ..........
  }

  ...and all the other extended array functions
);

Is there a way to solve this? :-/

Morten

A: 

You don't seem to be using the Array properties of the Array anyway, so you could just return an object instead:

var o = {
    test1: '1',
    test2: '2'
};
Tim Down
This array is supposed to be sent via AJAX so I really just want an assoc array with keys and values..Is there a way to accomplish that?Morten
Morten
Updated my answer.
Tim Down
I`ll try that!!
Morten
Is there a way to make a function that would make such a object for an assoc array that could also contain other arrays...I guess my example was lacking a little detail...Morten
Morten
In JavaScript, every object could be described as an associative array. There's nothing special about my example: it just creates a bog standard object and assigns properties to it, which can then be enumerted using `for...in`. Properties can be of any type, including Array.
Tim Down
I just did not see the possibilities in your example.. But I see it now!You where totally correct all along... :-)
Morten
A: 

Prototype extends the Array object's prototype, so it practically breaks the for(in) loops, and increases the risk that your own keys overlap. Start by reading why JavaScript "associative arrays" are considered harmful, and try using an Object instead of associative arrays.

Sending an object via AJAX.Request is done by simply passing it as the "parameters" option:

var myObj = {};
myObj['test'] = '1';
myObj['test2'] = '2';
new Ajax.Request([url], {
    parameters: myObj
});
Victor Stanciu
This was the solution! Thank you very much!
Morten
Well... It was allmost a solution!This does not work...var myObj = {};var myObj2 = {};myObj['test'] = '1';myObj['obj'] = myObj2;This will now only contain:Array( ['test'] => 1);What am I doing wrong? Or will it just not work this way?
Morten
You could do something like this:var myObj = {};var myObj2 = {"test2": 2};myObj['test'] = '1';myObj['obj'] = myObj2;new Ajax.Request([url], { parameters: {object: $H(myObj).toJSON()}});and then, on the server side, you will recieve the "object" parameter, which you can decode (json_decode if using PHP)
Victor Stanciu