Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

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.