Swap two objects in JavaScript
Asked Answered
P

5

8

I have the following code:

MyObject.prototype.doIt = function()
{
     var a = this.obj1;
     var b = this.obj2; 
}

How can i swap the values of this.obj1 and this.obj2 so obj1 becomes obj2 and obj2 becomes obj1.

!Note: Have in mind that i am not working with primitive types.

Porfirioporgy answered 22/4, 2013 at 16:9 Comment(0)
V
17

You can swap any number of objects or literals, even of different types, using a simple identity function like this:

var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);

This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.

Venessavenetia answered 15/12, 2013 at 23:58 Comment(1)
using this but like: const swap = x => x;Plauen
W
6

We can use about the destructing objects, like below code:

let a = 2;
let b = 4;
[a, b] = [b, a];
Watkins answered 20/7, 2020 at 2:54 Comment(0)
G
4

Use a temporary variable to hold the contents of one of the objects while swapping:

var tmp = this.obj1;
this.obj1 = this.obj2;
this.obj2 = tmp;
Goldman answered 22/4, 2013 at 16:15 Comment(0)
C
2

You can swap the properties easily enough:

MyObject.prototype.doIt = function()
{
     var a = this.obj1;
     var b = this.obj2;
     this.obj1 = b;
     this.obj2 = a;
}

That obj1 and obj2 are not primitive types is irrelevant. You don't actually need two variables:

MyObject.prototype.doIt = function()
{
     var a = this.obj1;
     this.obj1 = this.obj2;
     this.obj2 = a;
}

However, if any references to this.obj1 or this.obj2 already exist outside this code, they won't be swapped.

In terms of swapping this.obj1 and this.obj2 everywhere (including existing references), I don't think that can be done completely. You could strip out all properties of, say, this.obj1 (saving them somewhere), add in the properties from this.obj2, and then do the same for this.obj2. However, you won't be able to swap the prototypes, so objects cannot fundamentally swap identities.

Creative answered 22/4, 2013 at 16:13 Comment(2)
In fact, you could swap prototype with the use of Object.getPrototypeOf() and Object.setPrototypeOf(), but MDN strongly warn us it's a really bad idea for the application performance.Morass
@FélixBrunet - Hadn't thought about that. I guess it is possible to implement something like Smalltalk's become: method. Cool!Creative
P
0

Here is an example with concrete objects, say your original objects are 2 divs, div1 and div2.

To swap them,

var temp1 = div1;
var temp2 = div2;

div1 = temp2;
div2 = temp1;

Poree answered 20/9, 2013 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.