How to copy/clone a hash/object in JQuery?
Solution 1
Yes, extend an empty object with the original one; that way, everything will simply be copied:
var clone = $.extend({}, settings);
Extending some filled object with another, e.g.:
$.extend({a:1}, {b:2})
will return:
{a:1, b:2}
With the same logic:
$.extend({}, {foo:'bar', test:123})
will return:
{foo:'bar', test:123}
i.e. effectively a clone.
Solution 2
In a non jQuery way.
var newObj = {};
Object.keys(settings).forEach(function(key) {
newObj[ key ] = settings[ key ];
});
This copies only the top-level properties. To copy hashes with nested objects as property values, you will need to use a recursive function.
NB: The Object.keys(settings)
avoids the need for calling settings.hasOwnProperty(key)
.
Solution 3
var clone = $.extend(true, {}, settings);
Set first argument to true.
EDIT: First argument true
signifies deep copy. For given example in original question there is no need for deep copy since there are simple immutable key-value pairs. For question in title - as a general case - use deep copy. Otherwise you get half-copy.
Solution 4
It sounds like you want jQuery extend, which can copy an object for you.
http://api.jquery.com/jQuery.extend/
Solution 5
My 2 cents:
function clone(hash) {
var json = JSON.stringify(hash);
var object = JSON.parse(json);
return object;
}
It may not be the most optimized option but it can be handy for some scenarios.
at.
Updated on December 17, 2020Comments
-
at. over 3 years
I have a simple object (or hash) in Javascript:
var settings = { link: 'http://example.com', photo: 'http://photos.com/me.jpg' };
I need a copy of it. Is there a
settings.clone()
type method that will give me another object with the same attributes? I'm using jQuery, so happy to use a jQuery utility method if one exists. -
pimvdb over 12 years+1 Just to make sure,
hasOwnProperty
would be a good addition. (+1 tomorrow as I reached vote limit :)) -
Offirmo over 10 yearsOr even more expressive :
var new_obj = _.clone( old_obj );
-
Berry Tsakala about 10 yearsincorrect; contained objects are still passed by reference, and not deep-cloned, e.g. a={aa:{aaa:3}}; b=$extend({},a}; a.aa.aaa=4; b.aa.aaa==4 !!
-
Cheeso about 9 yearsI modified the code so that
hasOwnProperty
is no longer required. -
Mike Cluck over 8 yearsYou only need
true
if you want a deep copy. -
Florian Brucker over 8 years@BerryTsakala: Since JQuery 1.1.4 you can use
extend(true, ...)
to create deep copies. -
roberto tomás over 7 yearsfor most uses this is pretty good .. but it will miss keys with
undefined
as the value