var obj = {a: "hello", c: "test", num: 3, arr: [1, 2, 3, 4], anotherObj: {a: 35, str: "tester"}};
var deepClone = function(obj) {
var out = null;
if (Array.isArray(obj)) {
out = [];
for (var index = 0; index < obj.length; ++index) {
var subArray = obj[index];
out.push((typeof subArray === 'object') ? deepClone(subArray) : subArray);
}
} else {
out = {};
for (var key in obj) {
var subObject = obj[key];
out[key] = (typeof subObject === 'object') ? deepClone(subObject) : subObject;
}
}
return out;
};
function cloneArray(value) {
var newArray;
if (value && value.length) {
newArray = [];
for (var i = 0; i < value.length; i++) {
if (typeof value[i] === 'object') {
newArray[i] = Array.isArray(value[i]) ? cloneArray(value[i]) : cloneObject(value[i]);
} else {
newArray[i] = value[i];
}
}
} else if (value === null) {
newArray = null;
}
return newArray;
}
function cloneObject(value) {
var newObject;
if (value && typeof value === 'object' && Object.keys(value).length > 0) {
newObject = {};
for (var key in value) {
if (typeof value[key] === 'object') {
newObject[key] = Array.isArray(value) ? cloneArray(value[key]) : cloneObject(value[key]);
} else {
newObject[key] = value[key];
}
}
} else if (value && typeof value === 'object' && Object.keys(value).length === 0) {
newObject = {};
} else if (value === null) {
newObject = null;
}
return newObject;
}
function reduceDeepClone(obj) {
return Object.keys(obj).reduce((v, d) => Object.assign(v, {
[d]: (obj[d].constructor === Object) ? reduceDeepClone(obj[d]) : obj[d]
}), {});
}