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

前端 未结 6 2199
既然无缘
既然无缘 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: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).

提交回复
热议问题