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

前端 未结 6 2150
既然无缘
既然无缘 2021-02-05 00:52

I have a simple object (or hash) in Javascript:

var settings = {
  link: \'http://example.com\',
  photo: \'http://photos.com/me.jpg\'
};

I nee

相关标签:
6条回答
  • 2021-02-05 01:26

    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}
    
    0 讨论(0)
  • 2021-02-05 01:34

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

    0 讨论(0)
  • 2021-02-05 01:36

    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.

    0 讨论(0)
  • 2021-02-05 01:40

    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.

    0 讨论(0)
  • 2021-02-05 01:44
    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.

    0 讨论(0)
  • 2021-02-05 01:51

    It sounds like you want jQuery extend, which can copy an object for you.

    http://api.jquery.com/jQuery.extend/

    0 讨论(0)
提交回复
热议问题