Deep copying objects in Angular

前端 未结 9 2169
悲&欢浪女
悲&欢浪女 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

    I am faced with the problem of deep copying. angular.copy({}, factory) and angular.extend({}, factory) helps well for array or hashes objects, but when copying an object a calass, sometimes there may be problems with connected dependencies. I solved this problem so:

     copyFactory = (() ->
        resource = ->
          resource.__super__.constructor.apply this, arguments
          return
        this.extendTo resource
        resource
      ).call(factory)
    
    0 讨论(0)
  • 2020-12-01 09:40

    You can also use:

    JSON.parse(JSON.stringify(Object))

    if it's on your scope, it's in every Angular component, directive, etc. and it's also on every node environment.

    Unless you have a circular reference, it should work and will effectively dissociate your variable reference to the original object.

    0 讨论(0)
  • 2020-12-01 09:40

    If the source is an array of objects, using map:

    let cloned = source.map(x => Object.assign({}, x));
    

    OR

    let cloned = source.map((x) => {
                    return { ...x };
                 });
    
    0 讨论(0)
提交回复
热议问题