1

I have this:

var testArray = [];
testArray["First"] = "First Test Data";
testArray["Second"] = "Second Test Data";
$.toJSON(testArray);

I then pass it back to server side. When I look at the object server side in handling the AJAX request all I have is "[]".

Is there a way to do this or something similar to achieve the ability to look up data passed back from the client?

1
  • It sounds like your toJSON implementation is not converting to Json correctly. Commented Jun 1, 2011 at 19:05

2 Answers 2

5

You have to make testArray an object:

var testArray = {};

The way you use arrays is not correct. Arrays only should have values with numerical indices. Otherwise you just add a property to the array object and these are ignored when converted to JSON.

DEMO

Sign up to request clarification or add additional context in comments.

Comments

4

You are creating an array, but then you are using it as an object. Create an object instead, and it will be handled correctly:

var testObject = {};
testObject["First"] = "First Test Data";
testObject["Second"] = "Second Test Data";
$.toJSON(testObject);

or simply:

var testObject = {
  First: "First Test Data",
  Second: "Second Test Data"
};
$.toJSON(testObject);

If you really want an array, then you access the items using numbers, not strings:

var testArray = [];
testArray[0] = "First Test Data";
testArray[1] = "Second Test Data";
$.toJSON(testArray);

or simply:

var testArray = ["First Test Data", "Second Test Data"];
$.toJSON(testArray);

2 Comments

I had no idea! JavaScript let me use it happily for quite some time. How weird. Thanks for the examples!
@Sean Anderson: Yes, an array is also an object, so that usage is not an error (but may be confusing), but when the toJSON method serialises the array it will detect that it's an array and only include the array items, not it's object properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.