Organizational Research By

Surprising Reserch Topic

nodejs how to clone a object

nodejs how to clone a object  using -'javascript,node.js'

asked Sep 18, 2015 by deepak
0 votes

Related Hot Questions

7 Answers

0 votes

For utilities and classes where there is no need to squeeze every drop of performance, I often cheat and just use JSON to perform a deep copy:

function clone(a) {
   return JSON.parse(JSON.stringify(a));

This isn't the only answer or the most elegant answer; all of the other answers should be considered for production bottlenecks. However, this is a quick and dirty solution, quite effective, and useful in most situations where I would clone a simple hash of properties.

answered Sep 18, 2015 by yogeshplv
0 votes

There is no native method for cloning objects. Underscore implements _.clone which is a shallow clone.

_.clone = function(obj) {
  return _.isArray(obj) ? obj.slice() : _.extend({}, obj);

It either slices it or extends it.

Here's _.extend

// extend the obj (first parameter)
_.extend = function(obj) {
  // for each other parameter
  each(, 1), function(source) {
    // loop through all properties of the other objects
    for (var prop in source) {
      // if the property is not undefined then add it to the object.
      if (source[prop] !== void 0) obj[prop] = source[prop];
  // return the object (first parameter)
  return obj;

Extend simply iterates through all the items and creates a new object with the items in it.

You can roll out your own naive implementation if you want

function clone(o) {
  var ret = {};
  Object.keys(o).forEach(function (val) {
    ret[val] = o[val];
  return ret;

There are good reasons to avoid deep cloning because closures cannot be cloned.

I've personally asked a question about deep cloning objects before and the conclusion I came to is that you just don't do it.

My recommendation is use underscore and it's _.clone method for shallow clones

answered Sep 18, 2015 by balvant maurya
0 votes

There are some Node modules out there if don't want to "roll your own". This one looks good:

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!

answered Sep 18, 2015 by badhwar.rohit
0 votes

It's hard to do a generic but useful clone operation because what should be cloned recursively and what should be just copied depends on how the specific object is supposed to work.

Something that may be useful is

function clone(x)
    if (x === null || x === undefined)
        return x;
    if (x.clone)
        return x.clone();
    if (x.constructor == Array)
        var r = [];
        for (var i=0,n=x.length; i

In this code the logic is

  • in case of null or undefined just return the same (the special case is needed because it's an error to try to see if a clone method is present)
  • does the object have a clone method ? then use that
  • is the object an array ? then do a recursive cloning operation
  • otherwise just return the same value

This clone function should allow implementing custom clone methods easily... for example

function Point(x, y)
    this.x = x;
    this.y = y;


Point.prototype.clone = function()
    return new Point(this.x, this.y);

function Polygon(points, style)
    this.points = points; = style;


Polygon.prototype.clone = function()
    return new Polygon(clone(this.points),

When in the object you know that a correct cloning operation for a specific array is just a shallow copy then you can call values.slice() instead of clone(values).

For example in the above code I am explicitly requiring that a cloning of a polygon object will clone the points, but will share the same style object. If I want to clone the style object too instead then I can just pass clone(

answered Sep 18, 2015 by rajesh
0 votes

For a shallow copy, I like to use the reduce pattern (usually in a module or such), like so:

var newObject = Object.keys(original).reduce(function (obj, item) {
    obj[item] = original[item];
    return obj;

Here's a jsperf for a couple of the options:

answered Sep 18, 2015 by atulpariharmca
0 votes

Depending on what you want to do with your cloned object you can utilize the prototypal inheritence mechanism of javascript and achieve a somewhat cloned object through:

var clonedObject = Object.create(originalObject);

Just remember that this isn't a full clone - for better or worse.

A good thing about that is that you actually haven't duplicated the object so the memory footprint will be low.

Some tricky things to remember though about this method is that iteration of properties defined in the prototype chain sometimes works a bit different and the fact that any changes to the original object will affect the cloned object as well unless that property has been set on itself also.

answered Sep 18, 2015 by badhwar.rohit
0 votes

I implemented a full deep copy. I believe its the best pick for a generic clone method, but it does not handle cyclical references.

Usage example:

parent = {'prop_chain':3}
obj = Object.create(parent)
obj.a=0; obj.b=1; obj.c=2;

obj2 = copy(obj)

console.log(obj, obj.prop_chain)
// '{'a':0, 'b':1, 'c':2} 3
console.log(obj2, obj2.prop_chain)
// '{'a':0, 'b':1, 'c':2} 3

obj2.a = 15

console.log(obj, obj.prop_chain)
// '{'a':0, 'b':1, 'c':2} 4
console.log(obj2, obj2.prop_chain)
// '{'a':15, 'b':1, 'c':2} 4

The code itself:

This code copies objects with their prototypes, it also copy functions (might be useful for someone).

function copy(obj) {
  // (F.prototype will hold the object prototype chain)
  function F() {}
  var newObj;

  if(typeof obj.clone === 'function')
    return obj.clone()

  // To copy something that is not an object, just return it:
  if(typeof obj !== 'object' && typeof obj !== 'function' || obj == null)
    return obj;

  if(typeof obj === 'object') {    
    // Copy the prototype:
    newObj = {}
    var proto = Object.getPrototypeOf(obj)
    Object.setPrototypeOf(newObj, proto)
  } else {
    // If the object is a function the function evaluate it:
    var aux
    newObj = eval('aux='+obj.toString())
    // And copy the prototype:
    newObj.prototype = obj.prototype

  // Copy the object normal properties with a deep copy:
  for(var i in obj) {
    if(obj.hasOwnProperty(i)) {
      if(typeof obj[i] !== 'object')
        newObj[i] = obj[i]
        newObj[i] = copy(obj[i])

  return newObj;

With this copy I can't find any difference between the original and the copied one except if the original used closures on its construction, so i think its a good implementation.

I hope it helps

answered Sep 18, 2015 by abhimca2006