Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 254
at. Avatar asked Aug 18 '11 20:08

at.


People also ask

How do you clone an object in jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.

How does jQuery clone work?

The . clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.


2 Answers

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.

like image 195
pimvdb Avatar answered Sep 24 '22 23:09

pimvdb


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

like image 23
Pantelis Avatar answered Sep 24 '22 23:09

Pantelis