473,413 Members | 1,718 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

Deep Cloning an Object

17
How does one perform a deep clone (by value, not by reference) to an object in JavaScript?
Sep 28 '07 #1
8 7390
gits
5,390 Expert Mod 4TB
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 Expert Mod 4TB
hmm ... we have to improve it for properties that are arrays ... :)
Sep 29 '07 #3
gits
5,390 Expert Mod 4TB
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 Expert Mod 4TB
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
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 Expert Mod 4TB
you cannot clone dom-objects with that ... for that you can use regular dom methods ... cloneNode();

kind regards
Sep 29 '07 #7
scf1984
17
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 Expert Mod 4TB
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
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...
13
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
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...
1
by: Neven Klofutar | last post by:
Hi, Can please someone send me a link or an example of deep cloning. thanx, Neven
5
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...
2
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: ...
22
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 =...
3
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...
9
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...
3
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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...

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.