如何在JavaScript中深层复制自定义对象? [英] How to deep copy a custom object in JavaScript?

查看:66
本文介绍了如何在JavaScript中深层复制自定义对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这里冲浪一段时间,但仍然没有找到适合我的答案。

I've been surfing around here a while and still haven't found an answer that worked for me.

有没有办法深度复制非JS中的普通对象?

Is there any way to deep copy a non-plain object in JS?

我试过 jQuery.extend(true,{},this)但是它只克隆了其中一些,剩下的作为对另一个对象的引用。

I've tried jQuery.extend(true, {}, this) but it only cloned some of it, the rest remained as a reference to another object.

推荐答案

这里有3种不同的复制对象的方法。每种方法都有利弊,所以请仔细阅读并选择最适合您情况的方法

Here are 3 different methods for copying objects. Each method has pros and cons, so read through and pick the best for your situation

使用 Object.assign ,用于将所有可枚举的自有属性的值从一个或多个源对象复制到目标对象。这会复制值和函数。在撰写本文时,浏览器支持但不完美,但这是三者中最好的方法IMO。

Use Object.assign, which "is used to copy the values of all enumerable own properties from one or more source objects to a target object". This copies both values and functions. At the time of writing this, browser support is good but not perfect, but this is the best method IMO of the three.

const obj1 = {a:1, b:2};
const obj1Copy = Object.assign(obj1)

或者,您可以使用传播运算符从一个对象传播到另一个对象。请记住,这将复制键的值,但如果键的值是内存地址(另一个嵌套对象或数组),那么它只是一个浅的副本。

Alternatively, you can use the spread operator to spread from one object into another. Keep in mind that this will copy the values of keys, but if you the value of a key is a memory address (an other nested object or an array) then it will only be a shallow copy.

const obj1 = {a: () => {}, b:2}
const obj1Copy = { ...obj1 }

如果对象没有任何循环引用或函数作为值,则可以使用json stringify技巧:

If the object doesn't have any circular references or functions as values, you can use the json stringify trick:

let myCopy = JSON.parse(JSON.stringify(myObject));

不需要库,并且对大多数对象都有效。

No libraries required, and works very well for most objects.

这篇关于如何在JavaScript中深层复制自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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