Cloning JSON object in JavaScript

Blog / JavaScript ·

Simple and easy solution.

function clone(obj) {
    var outpurArr = new Array();
    for (var i in obj) {
      outpurArr[i] = typeof (obj[i]) == 'object' ? this.clone(obj[i]) : obj[i];
    }
    return outpurArr;
  }

The testing code:

function clone(obj) {
    var outpurArr = new Array();
    for (var i in obj) {
      outpurArr[i] = typeof (obj[i]) == 'object' ? this.clone(obj[i]) : obj[i];
    }
    return outpurArr;
  }
  var obj1 = {
    name: "aaa",
    getName: function () {
      return "The name is " + this.name;
    }
  }
  var obj2 = clone(obj1);
  obj1.name = "bbb";
  obj1.getName = function () {
    return "name=" + this.name;
  }
  document.write("------------ obj1" + obj1.getName());
  document.write("");
  document.write("------------ obj2" + obj2.getName());

And the result:

------------ obj1 name=bbb
------------ obj2The name is aaa

Krasimir Tsonev With over two decades of deep programming expertise, I offer comprehensive web consultancy and stack audits, alongside specialized workshops, training, and engaging public speaking to elevate your team's skills and optimize your digital presence. Contact me.

Keywords: obj obj1 outpurarr var document write obj2 object getname function return obj var outpurarr clone obj var function clone obj
Share the post on Twitter, Facebook, LinkedIn