How does one perform a deep clone (by value, not by reference) to an object in JavaScript?
8 7405 gits 5,390
Recognized Expert Moderator Expert
hi ...
you may use something like the following: -
var a = {
-
foo : { test: 1, test1: 2 },
-
bar : function(a) { alert(a) },
-
foobar: 'foobar1'
-
};
-
-
function clone_obj(obj) {
-
var c = {};
-
-
for (var i in obj) {
-
var prop = obj[i];
-
-
if (typeof prop == 'object') {
-
c[i] = clone_obj(prop);
-
} else {
-
c[i] = prop;
-
}
-
}
-
-
return c;
-
}
-
-
var b = clone_obj(a);
-
kind regards
ps: if you encounter problems with that let me know :)
gits 5,390
Recognized Expert Moderator Expert
hmm ... we have to improve it for properties that are arrays ... :)
gits 5,390
Recognized Expert Moderator Expert
improved version: -
var a = {
-
foo : { test: 1, test1: 2 },
-
bar : function(a) { alert(a) },
-
foobar: 'foobar1',
-
arr : [1, 2, 3, 4]
-
};
-
-
function clone_obj(obj) {
-
var c = {};
-
-
for (var i in obj) {
-
var prop = obj[i];
-
-
if (typeof prop == 'object') {
-
if (prop instanceof Array) {
-
c[i] = [];
-
-
for (var j = 0; j < prop.length; j++) {
-
c[i].push(prop[j]);
-
}
-
} else {
-
c[i] = clone_obj(prop);
-
}
-
} else {
-
c[i] = prop;
-
}
-
}
-
-
return c;
-
}
-
-
var b = clone_obj(a);
-
kind regards
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: -
var a = {
-
foo : { test: 1, test1: 2 },
-
bar : function(a) { alert(a) },
-
foobar: 'foobar1',
-
arr : [1, [8, 9], {1: 1, 2: 2}, 4]
-
};
-
-
function clone_obj(obj) {
-
var c = obj instanceof Array ? [] : {};
-
-
for (var i in obj) {
-
var prop = obj[i];
-
-
if (typeof prop == 'object') {
-
if (prop instanceof Array) {
-
c[i] = [];
-
-
for (var j = 0; j < prop.length; j++) {
-
if (typeof prop[j] != 'object') {
-
c[i].push(prop[j]);
-
} else {
-
c[i].push(clone_obj(prop[j]));
-
}
-
}
-
} else {
-
c[i] = clone_obj(prop);
-
}
-
} else {
-
c[i] = prop;
-
}
-
}
-
-
return c;
-
}
-
-
var b = clone_obj(a);
-
kind regards
arrrgh ... next testcase to check for :)
now the function is to be improved for the case that objects are contained i an array: -
var a = {
-
foo : { test: 1, test1: 2 },
-
bar : function(a) { alert(a) },
-
foobar: 'foobar1',
-
arr : [1, [8, 9], {1: 1, 2: 2}, 4]
-
};
-
-
function clone_obj(obj) {
-
var c = obj instanceof Array ? [] : {};
-
-
for (var i in obj) {
-
var prop = obj[i];
-
-
if (typeof prop == 'object') {
-
if (prop instanceof Array) {
-
c[i] = [];
-
-
for (var j = 0; j < prop.length; j++) {
-
if (typeof prop[j] != 'object') {
-
c[i].push(prop[j]);
-
} else {
-
c[i].push(clone_obj(prop[j]));
-
}
-
}
-
} else {
-
c[i] = clone_obj(prop);
-
}
-
} else {
-
c[i] = prop;
-
}
-
}
-
-
return c;
-
}
-
-
var b = clone_obj(a);
-
kind regards
Thanks, but this code gives me an error:
Error: too much recursion
When I try to clone a <td> object...
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
you cannot clone dom-objects with that ... for that you can use regular dom methods ... cloneNode();
kind regards
This one works.
Thanks :)
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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;
|
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...
|
by: Neven Klofutar |
last post by:
Hi,
Can please someone send me a link or an example of deep cloning.
thanx, Neven
|
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.
| |
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".
|
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();
|
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.
...
|
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...
|
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
{
...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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();...
|
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...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |