author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff.

Cloning JSON object in 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
If you enjoy this post, share it on Twitter, Facebook or LinkedIn. Or maybe comment below: