Cloning an Object in Node.js

The Solution to Cloning an Object in Node.js is

Possibility 1

Low-frills deep copy:

var obj2 = JSON.parse(JSON.stringify(obj1));

Possibility 2 (deprecated)

Attention: This solution is now marked as deprecated in the documentation of Node.js:

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().

Original answer::

For a shallow copy, use Node's built-in util._extend() function.

var extend = require('util')._extend;

var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5

Source code of Node's _extend function is in here:

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || typeof add !== 'object') return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  return origin;

~ Answered on 2013-02-23 12:40:28

Most Viewed Questions: