What's alternative to angular.copy in Angular

后端 未结 15 1187
忘掉有多难
忘掉有多难 2020-11-29 00:43

How can I copy an object and lose its reference in Angular?

With AngularJS, I can use angular.copy(object), but I\'m getting some error using that in An

15条回答
  •  无人及你
    2020-11-29 01:39

    As others have already pointed out, using lodash or underscore is probably the best solution. But if you do not need those libraries for anything else, you can probably use something like this:

      function deepClone(obj) {
    
        // return value is input is not an Object or Array.
        if (typeof(obj) !== 'object' || obj === null) {
          return obj;    
        }
    
        let clone;
    
        if(Array.isArray(obj)) {
          clone = obj.slice();  // unlink Array reference.
        } else {
          clone = Object.assign({}, obj); // Unlink Object reference.
        }
    
        let keys = Object.keys(clone);
    
        for (let i=0; i

    That's what we decided to do.

提交回复
热议问题