LoginSignup
2
2

More than 5 years have passed since last update.

Copy and clone object/array

Posted at
    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;
    }
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2