Nodejs: how to clone an object

后端 未结 12 2073
情书的邮戳
情书的邮戳 2020-12-04 18:32

If I clone an array, I use cloneArr = arr.slice()

I want to know how to clone an object in nodejs.

12条回答
  •  甜味超标
    2020-12-04 19:17

    Old question, but there's a more elegant answer than what's been suggested so far; use the built-in utils._extend:

    var extend = require("util")._extend;
    
    var varToCopy = { test: 12345, nested: { val: 6789 } };
    
    var copiedObject = extend({}, varToCopy);
    
    console.log(copiedObject);
    
    // outputs:
    // { test: 12345, nested: { val: 6789 } }
    

    Note the use of the first parameter with an empty object {} - this tells extend that the copied object(s) need to be copied to a new object. If you use an existing object as the first parameter, then the second (and all subsequent) parameters will be deep-merge-copied over the first parameter variable.

    Using the example variables above, you can also do this:

    var anotherMergeVar = { foo: "bar" };
    
    extend(copiedObject, { anotherParam: 'value' }, anotherMergeVar);
    
    console.log(copiedObject);
    
    // outputs:
    // { test: 12345, nested: { val: 6789 }, anotherParam: 'value', foo: 'bar' }
    

    Very handy utility, especially where I'm used to extend in AngularJS and jQuery.

    Hope this helps someone else; object reference overwrites are a misery, and this solves it every time!

提交回复
热议问题