Cloning an Object in Node.js

后端 未结 21 1840
情书的邮戳
情书的邮戳 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: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);
    
    0 讨论(0)
  • 2020-11-28 02:41

    There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone

    Looks like it handles all kinds of stuff, including circular references. From the github page:

    clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!

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

    If you're using coffee-script, it's as easy as:

    newObject = {}
    newObject[key] = value  for own key,value of oldObject
    

    Though this isn't a deep clone.

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