How to copy/clone a hash/object in JQuery? How to copy/clone a hash/object in JQuery? javascript javascript

How to copy/clone a hash/object in JQuery?


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.


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).


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.