Cloning Javascript Objects
Simple tip for clone javascript objects.
var clonedObject = JSON.parse(JSON.stringify(originalObject));
Written by Marcio Gasparotto
Related protips
2 Responses
var originalObject = {
div: document.createElement('div')
}
var clonedObject = JSON.parse(JSON.stringify(originalObject)); // TypeError: Converting circular structure to JSON
over 1 year ago
·
Hi!
This works great for a pojo:
var originalObject = {
items:[
{id:1, text:"Item 1" },
{id:2, text:"Item 2" }
],
other:{
foo:{
bar:'bar',
foo:'foo',
ary: [
[
{id:1, text:"Item 1" }, {id:2, text:"Item 2" }
],
[
{id:1, text:"Item 1" }, {id:2, text:"Item 2" }
]
]
}
}
}
var clonedObject = JSON.parse(JSON.stringify(originalObject));
In your case, a replacer maybe help you. Good luck!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#