Search code examples
javascriptjqueryasp.netpagemethodsjavascriptserializer

javascript pass by value instead of pass by reference having different javascript serialization string


I am using a javascript array as property of a javascript object. Whenever I modify the array it is affecting object property as it is passed by reference. So I cloned the object and set it as the object property.That problem is solved but now whenever I am trying to serialize the object I get different serialized string.

function Person(name, email, row) {
        this.Name = name;
        this.Email = email;

        var clonedRow = $.extend(true,{}, row);
        this.Row = clonedRow;
    }

    function FnClick() {
        var arr = new Array();
        arr[0] = "aaa";
        arr[1] = "bbb";

        var objPerson = new Person("Pallav", "P@abc.com", arr);
        arr[0] = "xxx";
        arr[1] = "zzz";

        var serializedObj = JSON.stringify(objPerson); //Sys.Serialization.JavaScriptSerializer.serialize(objPerson);
        var UserContext = new Array();
        PageMethods.TestMethod(serializedObj,onSuccess,OnFailure,UserContext);

    }

If I don't clone the row object and set it as it is the serializedObj string is

{"Name":"Pallav","Email":"P@abc.com","Row":["xxx","zzz"]}

and if I clone the object as above the serializedObj string is

{"Name":"Pallav","Email":"P@abc.com","Row":{"0":"aaa","1":"bbb"}}

Due to this the deserialized object in server side is different and row property of the object does not contain the 2 rows though it is in the serialized string.

How do I overcome this problem?


Solution

  • Change

    var clonedRow = $.extend(true,{}, row);
    

    to

    var clonedRow = $.extend(true,[], row);
    

    {} is an object ('associative array'), whereas [] is a simple/flat array.