Jack M. Jack M. -4 years ago 131
JSON Question

Cloning a json object and changing values mutates the original object as well

I was wondering why does this happen?

I have an json object stored in var myObj:

var myObj = JSON.parse(fs.readFileSync('json/data.json', 'utf8'));

then I take a clone from the original object by:

var modObj = myObj;

After that I remove empty values from clone:

cleansedObj = removeEmpty(modObj);

Why does this also mutate the original myObj and remove empty values from that too?

here is the function:

function removeEmpty(obj) {
Object.keys(obj).forEach(function(key) {
if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key])
else if (obj[key] === "") delete obj[key]
return obj;

I found a workaround by doing this, but seems like uneccesary operation:

var cleansedObj = JSON.stringify(myObj);
cleansedObj = removeEmpty(JSON.parse(cleansedObj));


Answer Source

You are not cloning you are just refering the same with new variable name.

Create a new object out of existing and use it

var modObj  = JSON.parse(JSON.stringify(myObj));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download