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.
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.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With