0

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?

2 Answers 2

2

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}}

Sign up to request clarification or add additional context in comments.

2 Comments

In your example the JSON.parse JSON.stringify combination is not required because you already assigne a new object to a. a = { b : a} should have the smae effect.
Thanks, @t.niese, don't know why i thought the JSON methods were needed.
2

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.

2 Comments

Which browser? In Firefox console.log does show me b.
@Scimonster — Whatever browser the OP is using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.