473,606 Members | 2,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deep Cloning an Object

17 New Member
How does one perform a deep clone (by value, not by reference) to an object in JavaScript?
Sep 28 '07 #1
8 7405
gits
5,390 Recognized Expert Moderator Expert
hi ...

you may use something like the following:

Expand|Select|Wrap|Line Numbers
  1. var a = {
  2.    foo   : { test: 1, test1: 2 },
  3.    bar   : function(a) { alert(a) },
  4.    foobar: 'foobar1'
  5. };
  6.  
  7. function clone_obj(obj) {
  8.     var c = {};
  9.  
  10.     for (var i in obj) {
  11.         var prop = obj[i];
  12.  
  13.         if (typeof prop == 'object') {
  14.            c[i] = clone_obj(prop);
  15.         } else {
  16.            c[i] = prop;
  17.         }
  18.     }
  19.  
  20.     return c;
  21. }
  22.  
  23. var b = clone_obj(a);
  24.  
kind regards

ps: if you encounter problems with that let me know :)
Sep 29 '07 #2
gits
5,390 Recognized Expert Moderator Expert
hmm ... we have to improve it for properties that are arrays ... :)
Sep 29 '07 #3
gits
5,390 Recognized Expert Moderator Expert
improved version:

Expand|Select|Wrap|Line Numbers
  1. var a = {
  2.    foo   : { test: 1, test1: 2 },
  3.    bar   : function(a) { alert(a) },
  4.    foobar: 'foobar1',
  5.    arr   : [1, 2, 3, 4]
  6. };
  7.  
  8. function clone_obj(obj) {
  9.     var c = {};
  10.  
  11.     for (var i in obj) {
  12.         var prop = obj[i];
  13.  
  14.         if (typeof prop == 'object') {
  15.            if (prop instanceof Array) {
  16.                c[i] = [];
  17.  
  18.                for (var j = 0; j < prop.length; j++) {
  19.                    c[i].push(prop[j]);
  20.                }
  21.            } else {
  22.                c[i] = clone_obj(prop);
  23.            }
  24.         } else {
  25.            c[i] = prop;
  26.         }
  27.     }
  28.  
  29.     return c;
  30. }
  31.  
  32. var b = clone_obj(a);
  33.  
kind regards
Sep 29 '07 #4
gits
5,390 Recognized Expert Moderator Expert
arrrgh ... next testcase to check for :)

now the function is to be improved for the case that objects are contained i an array:

Expand|Select|Wrap|Line Numbers
  1. var a = {
  2.    foo   : { test: 1, test1: 2 },
  3.    bar   : function(a) { alert(a) },
  4.    foobar: 'foobar1',
  5.    arr   : [1, [8, 9], {1: 1, 2: 2}, 4]
  6. };
  7.  
  8. function clone_obj(obj) {
  9.     var c = obj instanceof Array ? [] : {};
  10.  
  11.     for (var i in obj) {
  12.         var prop = obj[i];
  13.  
  14.         if (typeof prop == 'object') {
  15.            if (prop instanceof Array) {
  16.                c[i] = [];
  17.  
  18.                for (var j = 0; j < prop.length; j++) {
  19.                    if (typeof prop[j] != 'object') {
  20.                        c[i].push(prop[j]);
  21.                    } else {
  22.                        c[i].push(clone_obj(prop[j]));
  23.                    }
  24.                }
  25.            } else {
  26.                c[i] = clone_obj(prop);
  27.            }
  28.         } else {
  29.            c[i] = prop;
  30.         }
  31.     }
  32.  
  33.     return c;
  34. }
  35.  
  36. var b = clone_obj(a);
  37.  
kind regards
Sep 29 '07 #5
scf1984
17 New Member
arrrgh ... next testcase to check for :)

now the function is to be improved for the case that objects are contained i an array:

Expand|Select|Wrap|Line Numbers
  1. var a = {
  2.    foo   : { test: 1, test1: 2 },
  3.    bar   : function(a) { alert(a) },
  4.    foobar: 'foobar1',
  5.    arr   : [1, [8, 9], {1: 1, 2: 2}, 4]
  6. };
  7.  
  8. function clone_obj(obj) {
  9.     var c = obj instanceof Array ? [] : {};
  10.  
  11.     for (var i in obj) {
  12.         var prop = obj[i];
  13.  
  14.         if (typeof prop == 'object') {
  15.            if (prop instanceof Array) {
  16.                c[i] = [];
  17.  
  18.                for (var j = 0; j < prop.length; j++) {
  19.                    if (typeof prop[j] != 'object') {
  20.                        c[i].push(prop[j]);
  21.                    } else {
  22.                        c[i].push(clone_obj(prop[j]));
  23.                    }
  24.                }
  25.            } else {
  26.                c[i] = clone_obj(prop);
  27.            }
  28.         } else {
  29.            c[i] = prop;
  30.         }
  31.     }
  32.  
  33.     return c;
  34. }
  35.  
  36. var b = clone_obj(a);
  37.  
kind regards

Thanks, but this code gives me an error:
Error: too much recursion

When I try to clone a <td> object...
Sep 29 '07 #6
gits
5,390 Recognized Expert Moderator Expert
you cannot clone dom-objects with that ... for that you can use regular dom methods ... cloneNode();

kind regards
Sep 29 '07 #7
scf1984
17 New Member
you cannot clone dom-objects with that ... for that you can use regular dom methods ... cloneNode();

kind regards
This one works.
Thanks :)
Sep 29 '07 #8
gits
5,390 Recognized Expert Moderator Expert
hi ...

glad you got it working ... post back to the forum anytime you have more questions ...

kind regards
Sep 29 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
5428
by: Kevin | last post by:
Hi all, I've got a PHP4 app that I developed which I'm trying to get to run on a PHP5 server. Everything works great, except for one thing. There's a particular routine that creates an original object, then copies it. (The object constructor gets some meta information from the database, so I copy it for performance reasons). The routine then modifies the copies. PHP5 copies by reference by default, so this doesn't work--- I'm not
13
2181
by: ahaupt | last post by:
Hi all, I'm implementing the Clone() method through the ICloneable interface and don't quite know how deep I need to go for a deep copy. Example: class A: ICloneable { object _val;
1
2331
by: oDDskOOL | last post by:
I realized today that the Hashtable.Clone only produces a shallow copy... that makes me go mad that M$ doesn't even provide a deep copy ctor for the Hashtable class ! mighty tech ducks might reply "oh but what if the types in hastable don't have copy ctors defined? that could lead to dangerous situations". well, but was it a significant effort to provide a copy ctor / deep clone method to this class for objects that provide the...
1
1492
by: Neven Klofutar | last post by:
Hi, Can please someone send me a link or an example of deep cloning. thanx, Neven
5
25637
by: BenW | last post by:
Hello, What is the easiest way to make "deep copy" of my Hashtable? How about with other Collection classes in C#, any documents available? I don'r actually understand why Framework's Collection classes does not support deep copy methods by theself, only Clone with shallow copy.
2
10100
by: bonk | last post by:
I have come across the need to distinguish between the creation of a deep and a shallow copy and with great interest I have read this article: http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx This artivle seems to hint that I should not use System.IClonable but instead define my own interface(s) for cloning. Now since this article is rather old and since they did not obsolete IClonable there might be a new "best practise".
22
15923
by: Steven Blair | last post by:
I need to perform a Deep Copy on an ArrayList. I wrote a small sample app to prove this could be done: ArrayList a = new ArrayList(); ArrayList b = new ArrayList(); a.Add("Hello"); b = (ArrayList) a.Clone();
3
8744
by: raylopez99 | last post by:
The "C# Cookbook" (O'Reilly / Jay Hilyard), section 3.26, is on deep cloning versus shallow cloning. The scanned pages of this book are found here: http://www.sendspace.com/file/mjyocg (Word format, 3 pp) My question, coming from a C++ background where deep copying is done, is why in C# you would do either deep or shallow copying as suggested by O'Reilly (using the "ICloneable" inhereited interface), at least for the .NET framework. ...
9
13291
gits
by: gits | last post by:
This short article introduces a method that may be used to create a 'deep-copy' of an javascript object. You might ask: 'Wherefore do we need this?' ... Answer: 'Only variable-values of the basic data-types string, int, float, boolean and to make the confusion perfect :) functions too! are passed by value, all others are passed by reference.' This means, when you create an object a, like in the code below, and you assign object a to variable b...
3
2073
by: gasfusion | last post by:
Hey guys. I have a little problem trying to clone my object, which is shown below. If you notice below, i am using a generic linked list structure to store byte arrays. The problem is when i use my Clone() method to clone this object, it doesn't clone the actual LinkedList. Any ideas on how to go about fixing this? Much appreciated. using System; using System.Reflection; using System.Collections.Generic; namespace Compiler { ...
0
8439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8430
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8094
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8305
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5966
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5465
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3930
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1296
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.