Last Updated: January 20, 2020
·
645
· 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 ·