Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString()method is inherited by every object descended from Object. If this method is not overridden in a custom object,toString() returns “[object type]”, where type is the object type.
var toString = Object.prototype.toString;
function deepCopy(obj) {
var rv;
switch (typeof obj) {
case "object":
if (obj === null) {
// null => null
rv = null;
} else {
switch (toString.call(obj)) {
case "[object Array]":
// It's an array, create a new array with
// deep copies of the entries
rv = obj.map(deepCopy);
break;
case "[object Date]":
// Clone the date
rv = new Date(obj);
break;
case "[object RegExp]":
// Clone the RegExp
rv = new RegExp(obj);
break;
// ...probably a few others
default:
// Some other kind of object, deep-copy its
// properties into a new object
rv = Object.keys(obj).reduce(function (prev, key) {
prev[key] = deepCopy(obj[key]);
return prev;
}, {});
break;
}
}
break;
default:
// It's a primitive, copy via assignment
rv = obj;
break;
}
return rv;
}
var a = [1, { foo: "bar" }, ['a', 'b'], new Date()];
console.log(JSON.stringify(a));
var b = deepCopy(a);
b[1].foo = "updatebar";
console.log(JSON.stringify(b));
function deepCopy(obj) {
var rv;
switch (typeof obj) {
case "object":
if (obj === null) {
// null => null
rv = null;
} else {
switch (toString.call(obj)) {
case "[object Array]":
// It's an array, create a new array with
// deep copies of the entries
rv = obj.map(deepCopy);
break;
case "[object Date]":
// Clone the date
rv = new Date(obj);
break;
case "[object RegExp]":
// Clone the RegExp
rv = new RegExp(obj);
break;
// ...probably a few others
default:
// Some other kind of object, deep-copy its
// properties into a new object
rv = Object.keys(obj).reduce(function (prev, key) {
prev[key] = deepCopy(obj[key]);
return prev;
}, {});
break;
}
}
break;
default:
// It's a primitive, copy via assignment
rv = obj;
break;
}
return rv;
}
var a = [1, { foo: "bar" }, ['a', 'b'], new Date()];
console.log(JSON.stringify(a));
var b = deepCopy(a);
b[1].foo = "updatebar";
console.log(JSON.stringify(b));