如何不通过引用将 JavaScript 对象复制到新变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18359093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:37:05  来源:igfitidea点击:

How to copy JavaScript object to new variable NOT by reference?

javascriptobjectjavascript-objects

提问by Prusprus

I wrote a quick jsfiddle here, where I pass a small JSON object to a new variable and modify the data from the original variable (not the new variable), but the new variable's data gets updated as well. This must mean that the JSON object was passed by reference, right?

在这里写了一个快速的 jsfiddle ,我将一个小的 JSON 对象传递给一个新变量并修改原始变量(不是新变量)中的数据,但新变量的数据也会更新。这一定意味着 JSON 对象是通过引用传递的,对吗?

Here is my quick code:

这是我的快速代码:

var json_original = {one:'one', two:'two'}

var json_new = json_original;

console.log(json_original); //one, two
console.log(json_new); //one, two

json_original.one = 'two';
json_original.two = 'one';

console.log(json_original); //two, one
console.log(json_new); //two, one

Is there a way to make a deep copy of a JSON object so that modifying the original variable won't modify the new variable?

有没有办法制作 JSON 对象的深层副本,以便修改原始变量不会修改新变量?

回答by Andy

I've found that the following works if you're not using jQuery and only interested in cloning simple objects(see comments).

我发现如果您不使用 jQuery 并且只对克隆简单对象感兴趣(请参阅评论),则以下内容有效。

JSON.parse(JSON.stringify(json_original));

Documentation

文档

回答by Moeri

Your only option is to somehow clone the object.

您唯一的选择是以某种方式克隆对象。

See this stackoverflow questionon how you can achieve this.

请参阅有关如何实现此目标的stackoverflow 问题

For simple JSON objects, the simplest way would be:

对于简单的 JSON 对象,最简单的方法是:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

如果您使用 jQuery,则可以使用:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

2017 年更新:我应该提到,因为这是一个流行的答案,现在有更好的方法来使用较新版本的 javascript 来实现这一点:

In ES6 or TypeScript (2.1+):

在 ES6 或 TypeScript (2.1+) 中:

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraPropis also a property on oldObject, its value will not be used because the extraProp : "abc"is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

请注意,如果extraProp也是 oldObject 上的属性,则不会使用其值,因为extraProp : "abc"稍后在表达式中指定,这实际上覆盖了它。当然,oldObject 不会被修改。