Cloning an Object in Node.js

后端 未结 21 1838
情书的邮戳
情书的邮戳 2020-11-28 02:03

What is the best way to clone an object in node.js

e.g. I want to avoid the situation where:

var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
con         


        
相关标签:
21条回答
  • 2020-11-28 02:16
    npm install node-v8-clone
    

    Fastest cloner, it open native clone method from node.js

    var clone = require('node-v8-clone').clone;
    var newObj = clone(obj, true); //true - deep recursive clone
    
    0 讨论(0)
  • 2020-11-28 02:19

    I'm surprised Object.assign hasn't been mentioned.

    let cloned = Object.assign({}, source);
    

    If available (e.g. Babel), you can use the object spread operator:

    let cloned = { ... source };
    
    0 讨论(0)
  • 2020-11-28 02:19

    You can use the extend function from JQuery:

    var newClone= jQuery.extend({}, oldObject);  
    var deepClone = jQuery.extend(true, {}, oldObject); 
    

    There is a Node.js Plugin too:

    https://github.com/shimondoodkin/nodejs-clone-extend

    To do it without JQuery or Plugin read this here:

    http://my.opera.com/GreyWyvern/blog/show.dml/1725165

    0 讨论(0)
  • 2020-11-28 02:19

    Check out underscore.js. It has both clone and extend and many other very useful functions.

    This can be useful: Using the Underscore module with Node.js

    0 讨论(0)
  • 2020-11-28 02:20

    You can prototype object and then call object instance every time you want to use and change object:

    function object () {
      this.x = 5;
      this.y = 5;
    }
    var obj1 = new object();
    var obj2 = new object();
    obj2.x = 6;
    console.log(obj1.x); //logs 5
    

    You can also pass arguments to object constructor

    function object (x, y) {
       this.x = x;
       this.y = y;
    }
    var obj1 = new object(5, 5);
    var obj2 = new object(6, 6);
    console.log(obj1.x); //logs 5
    console.log(obj2.x); //logs 6
    

    Hope this is helpful.

    0 讨论(0)
  • 2020-11-28 02:21

    You can also use SugarJS in NodeJS.

    http://sugarjs.com/

    They have a very clean clone feature: http://sugarjs.com/api/Object/clone

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