Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove reference to another object in javascript

Tags:

javascript

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?

like image 911
Jack hardcastle Avatar asked Nov 30 '22 09:11

Jack hardcastle


2 Answers

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

var a = Object.assign({}, b);
like image 137
hsz Avatar answered Dec 08 '22 10:12

hsz


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))
like image 39
Allensy Avatar answered Dec 08 '22 09:12

Allensy