2

I'm trying to save an array which includes a object to a hidden field in a form. When I do so, the object doesn't show up, but is display like "[object Object]" instead.

arrayObject = [
    "something",
    { objectKey: "something else", otherObjectKey: "totally different" },
    "quite similar"
];

$("input").val(arrayObject);


This outputs

"something,[object Object],quite similar"

What can I do different?

1
  • Do you know what objects are and how they work? Commented Dec 12, 2011 at 10:50

2 Answers 2

3

Set it into the hidden field after serializing it as JSON like this:

$("input").val(JSON.stringify(arrayObject));

And parse it into the arrayObject while reading it back like this:

var savedArray = JSON.parse($("input").val());
Sign up to request clarification or add additional context in comments.

8 Comments

Worth noting that json2.js is required to ensure that JSON.stringify() and JSON.parse() work in all browsers.
Thanks. Yes, json2.js will be required in older versions of browsers. Newer versions have these JSON methods built-in. Forgot to point that out! :)
@jakeclarkson: Which browers are you refering to? I tried it in IE7, 8, 9, Opera 11, Firefox 8, Safari 5.1.2 and Chrome 15 and it worked in all of those.
As you've correctly pointed out all modern browsers will have native support for the JSON Object. In terms of browsers that don't support it: IE6 is the one that springs to mind; if anyone is unfortunate enough to be using this still :-). By including the file you have peace of mind that JSON.stringify() and JSON.parse() are always available.
I'm not optimizing for ie6 no longer, so that's fine by me... Thanks for the concern though.
|
-1

$("input").val(JSON.stringify(arrayObject))

Comments

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.