[英]How to make a deep copy of a object in Javascript
I want to make a deep copy of a object, say I have a object:我想做一个 object 的深拷贝,假设我有一个 object:
const oriObj = {
id: 1,
version: 1,
person: 'jack'
};
so after a click event
, oriObj
is set to be a empty array []
, but I still want to get the original value in the oriObj
for example the id and version.所以在
click event
之后, oriObj
被设置为一个空数组[]
,但我仍然想在oriObj
中获取原始值,例如 id 和版本。 I was trying to make a deep copy, so the no matter how oriObj
is changing, once I am getting the value of oriObj in the beginning, I deep copy it and store in so it won't become empty array.我试图做一个深拷贝,所以无论
oriObj
如何变化,一旦我一开始就得到 oriObj 的值,我就深拷贝它并存储进去,这样它就不会变成空数组。 I have tried several method, but it won't work, I am still getting empty array after the click event.我尝试了几种方法,但都行不通,点击事件后我仍然得到空数组。
If it's a simple object with no methods, one quick way is to serialize the object and then parse it again.如果它是一个没有方法的简单 object,一种快速的方法是序列化 object,然后再次解析它。
const oriObj = { id: 1, version: 1, person: 'jack' }; const copy = JSON.parse(JSON.stringify(oriObj)); oriObj.id = "changed this"; console.log(oriObj, copy);
I want to make a deep copy of a object, say I have a object:我想制作一个 object 的深层副本,假设我有一个 object:
const oriObj = {
id: 1,
version: 1,
person: 'jack'
};
so after a click event
, oriObj
is set to be a empty array []
, but I still want to get the original value in the oriObj
for example the id and version.所以在
click event
之后, oriObj
被设置为一个空数组[]
,但我仍然想获取oriObj
中的原始值,例如 id 和版本。 I was trying to make a deep copy, so the no matter how oriObj
is changing, once I am getting the value of oriObj in the beginning, I deep copy it and store in so it won't become empty array.我试图做一个深拷贝,所以不管
oriObj
是如何变化的,一旦我一开始就得到了 oriObj 的值,我就会把它深拷贝并存储起来,这样它就不会变成空数组。 I have tried several method, but it won't work, I am still getting empty array after the click event.我尝试了几种方法,但它不起作用,点击事件后我仍然得到空数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.