-2

I was having a problem where JSON.stringify was not retaining a property I added to an object that was created using $("#myForm").serializeArray();.

I found this SO thread: JSON.stringify is ignoring object properties

And the solution worked for me -- I created a new object which extended my mySerializedFormArray object, then I was able to call delete newObj.toJSON.

If I simply called delete mySerializedFormArray.toJSON;, the new property I added is still removed during stringification.

Why does it work when I extend the object?

Edit:

var DynExport = $('#frmDynExport').serializeArray();

DynExport.IsFooEnabled = $("#hdnFooFlag").val();

var newObj = $.extend({}, DynExport);

delete newObj.toJSON;

var someOtherVar = JSON.stringify(newObj);
DynExport = JSON.stringify(DynExport);

someOtherVar will include IsFooEnabled, DynExport does not.

Community
  • 1
  • 1
sab669
  • 3,984
  • 8
  • 38
  • 75
  • 3
    You should post the actual code involved. – Pointy Oct 21 '16 at 18:02
  • @Pointy Done. I figured since I'm just using the exact code in the thread I linked it wasn't really needed. – sab669 Oct 21 '16 at 18:07
  • Could the object you want to delete from be frozen via Object.freeze? That would make sense here, and copying everything into a new (non-frozen) object would work. – Joe Attardi Oct 21 '16 at 18:10
  • 1
    What's all this about `.toJSON`? The return value from jQuery's `.serializeArray()` won't have a `toJSON` method, and for that matter neither will the object you pass in to `$.extend()`. – Pointy Oct 21 '16 at 18:13

1 Answers1

2

The .serializeArray() method returns an array (which is probably not surprising). When an array is serialized as JSON, it ends up looking like this:

[ value, value, value, ... ]

The property names are the numeric indexes of the values in the array, and they're implicit: the first value corresponds to element 0, the second to element 1, and so on.

In that scheme of representation, then, there's no place to put properties that don't have numeric names; that is, properties that aren't part of the "real" array. Such properties work fine in JavaScript of course, but there's simply no way to represent them in JSON.

By copying the array properties (along with your "IsFooEnabled" property) to a new plain object with $.exend(), you get around that problem because the JSON serialization scheme for a plain object explicitly includes all the property names.

Pointy
  • 405,095
  • 59
  • 585
  • 614