-2

I have an object playerInfoObject with properties w1 and w2, which are also objects.

I need to change their places between each other

They become equal when I'm trying to do this:

    var tmp = playerInfoObject.w1;
    playerInfoObject.w1 = playerInfoObject.w2;
    playerInfoObject.w2 = tmp;

How can I solve this problem?

Thank you in advance

weratius
  • 113
  • 1
  • 12

2 Answers2

0

If you can use EcmaScript 6, a destructuring assignment can solve it without a temporary variable:

playerInfoObject = {
  w1: {w: '1'},
  w2: {w: '2'}
};

[playerInfoObject.w1, playerInfoObject.w2] = [playerInfoObject.w2, playerInfoObject.w1];

Or with object destructuring directly:

({w1: playerInfoObject.w2, w2: playerInfoObject.w1}) = playerInfoObject;

Otherwise, your code seems to be working fine.

nils
  • 25,734
  • 5
  • 70
  • 79
  • thank you, but I can't use that. Couldn't you check that out http://jsfiddle.net/Costa595/62zxdoqz/, that still doesn't help – weratius Oct 13 '15 at 08:13
  • It doesn't work, partially because you haven't defined `playerInfoObject`. – nils Oct 13 '15 at 08:25
  • ...and because you hadn't loaded jQuery in your fiddle. Here is a working example: https://jsfiddle.net/62zxdoqz/1/ – nils Oct 13 '15 at 08:38
  • I meant that it doesn't work properly in my project, in jsfiddle I just wanted to show the code and that's all – weratius Oct 13 '15 at 11:13
  • I'm still not understand *what* isn't working... can you provide a full example I can test where it doesn't work the way you expect it to? – nils Oct 13 '15 at 12:18
0

= operator places a reference between the object, you need to clone it.

var tmp = JSON.decode(JSON.encode(playerInfoObject.w1));
playerInfoObject.w1 = JSON.decode(JSON.encode(playerInfoObject.w2));
playerInfoObject.w2 = tmp;

You can find more elegant ways of cloning objects but this should work.

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
Jacob
  • 994
  • 1
  • 8
  • 20