问题
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.
回答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.
回答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).
回答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.
回答4:
It sounds like you want jQuery extend, which can copy an object for you.
http://api.jquery.com/jQuery.extend/
回答5:
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}
回答6:
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.
来源:https://stackoverflow.com/questions/7113865/how-to-copy-clone-a-hash-object-in-jquery