Deep copying objects in Angular

前端 未结 9 2194
悲&欢浪女
悲&欢浪女 2020-12-01 08:58

AngularJS has angular.copy() to deep copy objects and arrays.

Does Angular also have something like that?

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 09:34

    Another option is to implement your own function:

    /**
     * Returns a deep copy of the object
     */
    public static deepCopy(oldObj: any) {
        var newObj = oldObj;
        if (oldObj && typeof oldObj === "object") {
            if (oldObj instanceof Date) {
               return new Date(oldObj.getTime());
            }
            newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
            for (var i in oldObj) {
                newObj[i] = this.deepCopy(oldObj[i]);
            }
        }
        return newObj;
    }
    

提交回复
热议问题