I was wondering why does this happen?
I have an 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));
Thanks!