6
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?

Jack hardcastle
  • 2,748
  • 4
  • 22
  • 40
  • 1
    its better you perfrom copy operation..i.e. copy object rather than assigning reference...this is for cloning object please check : http://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object – Pranay Rana Jun 30 '16 at 12:00
  • You have to make copy of variable. How to clone object you can see [here](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – Domas Mar Jun 30 '16 at 12:00

3 Answers3

17

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

var a = Object.assign({}, b);
str
  • 42,689
  • 17
  • 109
  • 127
hsz
  • 148,279
  • 62
  • 259
  • 315
11

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))
Szymon
  • 170
  • 9
Allensy
  • 187
  • 2
  • 10
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.

Keks
  • 61
  • 1
  • 1