克隆json对象和更改值也会改变原始对象 [英] Cloning a json object and changing values mutates the original object as well

查看:121
本文介绍了克隆json对象和更改值也会改变原始对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么会这样?

I was wondering why does this happen?

我有一个存储在var myObj中的json对象:

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);

为什么这也会改变原来的myObj并从中删除空值?

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

这里是函数:

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));

谢谢!

推荐答案

你没有克隆你只是用新的变量名来引用它。

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));

这篇关于克隆json对象和更改值也会改变原始对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆