I have a simple object (or hash) in Javascript:
var settings = {
link: \'http://example.com\',
photo: \'http://photos.com/me.jpg\'
};
I nee
Underscore.js also has an extend function if you are not using jQuery:
extend
_.extend(destination, *sources)
Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments._.extend({name: 'moe'}, {age: 50}); => {name: 'moe', age: 50}
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)
.
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.
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.
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.
It sounds like you want jQuery extend, which can copy an object for you.
http://api.jquery.com/jQuery.extend/