How to clone or copy an object in JavaScript?
Jul 13, 2025 am 01:18 AMTo copy JavaScript objects, you need to select the method according to your needs. 1. Use Object.assign() for shallow copying, only top-level attributes are copied, nested references are still shared; 2. Extended operators achieve the same effect, and the writing is more concise; 3. Deep copying requires JSON serialization (ignoring special content such as functions), third-party libraries such as lodash's cloneDeep() (processing complex structures) or custom recursive functions (be aware of circular reference issues). Shallow copies are suitable for simple structures, and deep copies are used for nested or completely isolated scenes.
Copying or cloning an object in JavaScript is a common requirement in development. Using the assignment operator directly ( =
) does not really create a new object, but allows two variables to point to the same memory address, so modifying one of them will affect the other. To achieve true replication, you need to choose the appropriate method according to the specific needs.

1. Use Object.assign()
for shallow copying
If you only need to copy the first layer of the object, you can use Object.assign()
method:
const original = { name: 'Alice', age: 25 }; const copy = Object.assign({}, original);
This method is suitable for scenarios where no nested structure copy is required. But be aware that if the object contains reference types (such as arrays, objects), these nested values will still be shared.

For example:
const original = { user: { name: 'Bob' } }; const copy = Object.assign({}, original); copy.user.name = 'Tom'; console.log(original.user.name); // Output Tom, because user is a reference type
2. Use Spread Operator
Similar to Object.assign()
, the extension operator provides a more concise way of writing:

const original = { id: 1, info: { role: 'admin' } }; const copy = { ...original };
It is also a shallow copy and does not work for nested objects. Suitable for cases where only top-level attributes are copied.
3. Several ways to achieve deep copy
When you need to completely copy the entire object, including the nested structure inside, you need to use "deep copy".
- Deserialization with JSON
Here is a simple but limited way:
const copy = JSON.parse(JSON.stringify(original));
This method ignores special content such as functions, undefined
, circular references, etc., so it is not applicable in some complex scenarios, but it is sufficient for pure data objects.
- Using third-party libraries
For more complex object structures, it is recommended to use cloneDeep()
method like lodash :
const _ = require('lodash'); const deepCopy = _.cloneDeep(original);
This method is more stable and can handle most edge cases.
- Custom recursive functions (advanced)
If you want to implement a deep copy function yourself, you can copy each property layer by layer by layer by recursion:
function deepClone(obj) { if (typeof obj !== 'object' || obj === null) return obj; const copy = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = deepClone(obj[key]); } } return copy; }
Note: This version does not deal with the problem of circular references, and it is recommended to use mature solutions in actual projects.
Basically that's it
There are many ways to copy objects in JavaScript. Which one you choose depends on whether you need deep copy, the complexity of your code, and the performance requirements. Shallow copies are suitable for simple object structures, while deep copies are more suitable for nested objects or scenarios where the original objects are completely isolated.
The above is the detailed content of How to clone or copy an object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl
