sab669 sab669 - 9 months ago 35
Javascript Question

Why must you extend an object in order to delete a member of it?

I was having a problem where

was not retaining a property I added to an object that was created using

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
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?


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

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

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

delete newObj.toJSON;

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

will include
does not.

Answer Source

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.