miquelarranz
miquelarranz

Reputation: 894

Javascript assignation issue

I was trying to change the structure of a Javascript object and I don't understand the results I am receiving from the logs.

I have the following object: a = {e: 1, f: 2}

And I want to move it to a.b

If I do a.b = a then I receive these results:

console.log(a) // {e: 1, f: 2}
console.log(a.b) // {e: 1, f: 2}

While I am expecting something like this:

console.log(a) // {b: {e: 1, f: 2}}
console.log(a.b) // {e: 1, f: 2}

Can someone explain me why this is happening?

Upvotes: 0

Views: 74

Answers (2)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

a.b = a simply assigns a.b as a reference to a, which causes a to become a recursive object:

var a = {e: 1, f: 2};
a.b = a;

console.log(a.e, a.f);  //1 2
console.log(a.b.e, a.b.f);  //1 2
console.log(a.b.b.e, a.b.b.f);  //1 2
console.log(a.b.b.b.e, a.b.b.b.f);  //1 2

To actually move a's properties into a.b, you'll need to overwrite the existing object, assigning a new property b to its existing value:

var a = {e: 1, f: 2};

a = {b: a};

console.log(a);  //{b: {e: 1, f: 2}}

Upvotes: 2

Quentin
Quentin

Reputation: 943569

Assigning a value in JS doesn't move it, it copies it.

You are adding a b property to the existing object.

It isn't shown in the log because console.log protects itself against infinite recursion by not displaying the property.

Upvotes: 2

Related Questions