How to Clone Variables (The Clone Function) in Javascript?


JS How to Clone Variables (The Clone Function) in Javascript? javascript

NodeJs / Javascript

To Deep Copy a variable in Javascript, we have to first check its type – if it is an Array, we then need to clone each element in the array as a new copy and if it is an Object, we have to iterate the keys and assign a cloned copy (deep copy) to the new object. It is primitive type e.g. int, float, we can just return a value – copy by value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function clone(Obj) {
  let buf; // the cloned object
  if (Obj instanceof Array) {
    buf = []; // create an empty array
    var i = Obj.length;
    while (i --) {
      buf[i] = clone(Obj[i]); // recursively clone the elements
    }
    return buf;
  } else if (Obj instanceof Object) {
    buf = {}; // create an empty object
    for (const k in Obj) {
      if (obj.hasOwnProperty(k)) { // filter out another array's index
        buf[k] = clone(Obj[k]); // recursively clone the value
      }     
    }
    return buf;
  } else {
    return Obj;
  }
}
function clone(Obj) {
  let buf; // the cloned object
  if (Obj instanceof Array) {
    buf = []; // create an empty array
    var i = Obj.length;
    while (i --) {
      buf[i] = clone(Obj[i]); // recursively clone the elements
    }
    return buf;
  } else if (Obj instanceof Object) {
    buf = {}; // create an empty object
    for (const k in Obj) {
      if (obj.hasOwnProperty(k)) { // filter out another array's index
        buf[k] = clone(Obj[k]); // recursively clone the value
      }     
    }
    return buf;
  } else {
    return Obj;
  }
}

Example usage:

1
2
var a = [1, 2, "abc", { "a" : [b, 3, 4] }, true];
var b = clone(a);
var a = [1, 2, "abc", { "a" : [b, 3, 4] }, true];
var b = clone(a);

It should be noted that when cloning the elements of array, and the values in an Object, we have to recursively call the function to clone the value – as the element could be another array or Object, or any other types e.g. booleans – who knows how weird the Javascript can get.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
318 words
Last Post: How to restore SQL database backup by using SQL Server Management Studio?
Next Post: C# How to Remove Empty Elements from List in O(n)?

The Permanent URL is: How to Clone Variables (The Clone Function) in Javascript?

Leave a Reply