7
var b = {};
var a = b;
b.test = 123;
console.log(a.test);

I am trying to write code similar to the above, however for sake of not having to describe context I'll display that instead ^

After the line a = b I want to lose the reference from a to b, so I can update b without it affecting a, and vice-versa

Is this possible?

2
  • 1
    its better you perfrom copy operation..i.e. copy object rather than assigning reference...this is for cloning object please check : stackoverflow.com/questions/728360/… Commented Jun 30, 2016 at 12:00
  • You have to make copy of variable. How to clone object you can see here Commented Jun 30, 2016 at 12:00

4 Answers 4

18

You can clone your object with Object.assign():

var a = Object.assign({}, b);
Sign up to request clarification or add additional context in comments.

3 Comments

But be aware that this is an ES6 feature and currently not available in all browsers (e.g. Internet Explorer).
@LUH3417 Yes that would be necessary.
It may not work as expected for deep objects.
13

You can use JSON.stringify(obj) and then JSON.parse to the string. So it'll be something like that:

let obj= {
    hello: 'hello'
};
let string = JSON.stringify(obj);
let newObj = JSON.parse(string);

Or a shorter, one-line way:

let newObj = JSON.parse(JSON.stringify(obj))

1 Comment

Wouldn't retain functions.
5

Using Object.assign(), Object.create() or spread operator will not help you with arrays in objects (works with non-array properties though).

let template = {
    array: []
};
let copy = { ...template };
console.log(template.array); // As expected, results in: []
copy.array.push(123);
console.log(template.array); // Output: [123]

But this can be solved using JSON.stringify() and JSON.parse(), as already said.

let template = {
    array: []
};
let copy = JSON.parse(JSON.stringify(template));
console.log(template.array); // Output: []
copy.array.push(123);
console.log(template.array); // Output: [] 

Wonder if it is the most adequate solution... Excuses if I'm missing something, am only a beginner.

1 Comment

works fantastic for array. life saving...
1

structuredClone() is now a newer and better way to copy objects without reference.

var a = structuredClone(b);

More here: https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

Comments

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.