Cloning an Object in Node.js

后端 未结 21 1924
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-11-28 02:40

    There is also a project on Github that aims to be a more direct port of the jQuery.extend():

    https://github.com/dreamerslab/node.extend

    An example, modified from the jQuery docs:

    var extend = require('node.extend');
    
    var object1 = {
        apple: 0,
        banana: {
            weight: 52,
            price: 100
        },
        cherry: 97
    };
    
    var object2 = {
        banana: {
            price: 200
        },
        durian: 100
    };
    
    var merged = extend(object1, object2);
    

提交回复
热议问题