1

I have this fun :

swapjson = function (j1,j2) 
{ var jj = JSON.parse(JSON.stringify(j1));
  j1 = JSON.parse(JSON.stringify(j2));
  j2 = jj;  
}

I have also:

var myjson1 = {'x':1000, 'y':1000};
var myjson2 = {'x':2000, 'y':-2000};

swapjson (myjson1,myjson2);
console.log myjson1.x

1000 ?????

And I discover that inside the swapjson function the swap is made but not after call.

What is happen ? I dont understand what I'm doing bad... Any help would be appreciated.

civiltomain
  • 1,136
  • 1
  • 9
  • 27
  • 1
    You don't have JSON, you have objects, but you're parsing them to JSON and back to avoid having copies of references, which seems like it's not a very good idea. – adeneo Nov 13 '14 at 11:33
  • 1
    see this: http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language Luca – Luca Rasconi Nov 13 '14 at 11:48

2 Answers2

1

You can't replace the entire object like that, as the object itself isn't passed by referenced.
You can however change properties of the object passed, and it will stick, as a copy of the object is passed in.

So instead of parsing to strings and back to objects you can just iterate over the two objects keys, and replace one by one

swapjson = function (j1, j2) {
    var temp = {};

    for (key in j1) {
        temp[key] = j1[key];
        delete(j1[key]);
    }
    for (key in j2) {
        j1[key] = j2[key];
        delete(j2[key]);
    }

    for (key in temp) {
        j2[key] = temp[key];
    }

}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You copy the value of myjson1 (which is a reference to an object and nothing to do with JSON) into j1, and the value of myjson2 into j2.

Then you overwrite the value of j1 and the value of j2.

You never change the values of myjson1 or myjson2.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335