The best way to clone an object in JavaScript?
Introduction
What is the best way to clone a JavaScript object? We have seen some recursive copying function with various flaws. But, what is the best way to clone an object in JavaScript?
Solution 1 - Use jQuery $.extend()
If you wish to have a fast object clone, you can use jQuery $.extend()
.
// Shallow copy
var newObject = $.extend({}, oldObject);
// Deep copy
var newObject = $.extend(true, {}, oldObject)
Note: the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (for example: trying to deep extend a DOM element). It's used frequently in jQuery core and in plugins to great effect. More information can be found in the jQuery documentation.
Solution 2 - Use stringify()
and parse()
Assuming that you have only variables and not any functions or Date in your object, you can just use:
var newObject = JSON.parse(JSON.stringify(oldObject));
Above solution is the better than deep copy an object (it beats out JQuery.extend with deep flag set true by 10-20%).
Note: Beware using the JSON.parse(JSON.stringify(obj))
method on Date
objects - JSON.stringify(new Date())
returns a string representation of the date in ISO format, which JSON.parse()
doesn't convert back to a Date object.
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync