user544079 user544079 - 4 years ago 111
Javascript Question

Create clone of an object in Javascript

In Javascript

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.slice();


arr2
will not change if
arr
values are changed. i.e
arr[0] = 0;
, still
arr2[0] == 1; // true
.

Consider this:

var obj = {name: 'John', company: 'XYZ'};
var obj2 = obj; // Creates a duplicate of obj


But
obj.name = 'Dave'
, makes
obj2.name = 'Dave'
as well.

How can we do a
slice()
operation for objects?

Answer Source

To clone objects (excluding functions and prototypes) you should use structured clone.

For node.js I have found this package, but I can't tell you if it is good.

For browsers you can use this asynchronous clone function (it depends on correct implementation of postMessage):

function clone(obj, callback) {
    var from = window.location.origin;
    var wrapper = {'__clone__': true};
    wrapper.__data__ = obj;
    var listener = function(e) {
        if(e.origin === from && e.data.__clone__) {
            callback(e.data.__data__);
            window.removeEventListener('message', listener);
        }
    };
    window.addEventListener('message', listener);
    window.postMessage(wrapper, from);
}

Structured clone supports:

  • primitives
  • new String, new Boolean, new Number
  • new Date
  • new RegExp
  • new Blob
  • new File
  • new FileList
  • new ArrayBuffer
  • TypedArrays
  • ImageData
  • Arrays
  • plain objects
  • Map
  • Set
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download