Last Updated: January 20, 2020
·
853
· gasparotto

Cloning Javascript Objects

Simple tip for clone javascript objects.

var clonedObject = JSON.parse(JSON.stringify(originalObject));

2 Responses
Add your response

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
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