Posted at

Copy and clone object/array

More than 5 years have passed since last update.

    var objProto = Object.prototype,

arrProto = Array.prototype,
toString = objProto.toString,

function isObj(obj) {

if (toString.call(obj) === '[object Object]') {
return true;
}

return false;
}
function isArray(obj) {

if (toString.call(obj) === '[object Array]') {
return true;
}

return false;
}

function copy(base, target, opt) {

var key, i, l;

opt || (opt = {});

for (key in target) if (target.hasOwnProperty(key)) {

if (base[key] && !opt.overwrite) {
continue;
}

if (isObj(target[key]) && opt.deepCopy) {
base[key] = copy({}, target[key]);
}
else if (isArray(target[key])) {
if (opt.deepCopy) {
base[key] = [];

for (i = 0, l = target[key].length; i < l; i++) {
if (isObj(target[key][i])) {
base[key].push(copy({}, target[key][i]));
}
else {
base[key].push(target[key][i]);
}
}
}
else {
base[key] = target[key];
}
}
else {
base[key] = target[key];
}
}

return base;
}