Skip to content

JavaScript clone object without reference | Example code

  • by

Use JSON.parse() and JSON.stringify() methods to clone objects without reference in JavaScript.If you use a = statement to assign a value to a var with an object on the right side, javascript will not copy but reference the object.

JSON.parse(JSON.stringify(json_original));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

JavaScript clone object without reference

Simple example code not using jQuery and only interested in cloning simple objects.

<!DOCTYPE html>
<html>
<body>

  <script>
    var json_original = {one:'one', two:'two'}
    
    var clone = JSON.parse(JSON.stringify(json_original));

    console.log(clone)

  </script>

</body>
</html> 

Output:

JavaScript clone object without reference

Note: using JSON.parse(JSON.stringify(obj)) may work but is costly, and might throw a TypeError as in

const a = {};
const b = { a };
a.b = b;
const clone = JSON.parse(JSON.stringify(a));
/* Throws
Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property 'b' -> object with constructor 'Object'
    --- property 'a' closes the circle
    at JSON.stringify (<anonymous>)
    at <anonymous>:4:6
*/

Deep copying an Object

To deep copy an object we need to use JSON.parse() and JSON.stringify() methods.

Example:

const obj = {a:1,b:2,c:{d:3}};

const deepClone = JSON.parse(JSON.stringify(obj));

Now if we change obj.c.d property value the deepClone object property value remains unchanged because there is no reference to the original object.

obj.c.d = 35;

// d value is changed
console.log(obj); // {a:1,b:2,c:{d:35}}

// d value remains unchanged because there is no reference
console.log(deepClone); // {a:1,b:2,c:{d:3}}

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *