Cloning objects TypeScript

This question already has an answer here:

  • What's alternative to angular.copy in Angular 8 answers
  • What is the most efficient way to deep clone an object in JavaScript? 57 answers

  • Try using

    this.user = Object.assign({}, currentObject);
    

    As mentioned by @AngularFrance, this will only work for shallow-copying objects, seek another implementation if there's a need to deep-copy an object.


    You can use lodash :

    https://lodash.com/docs#cloneDeep

    lodash is recommended for lot of objects / array manipulations


    You could bind your editor form to an empty User object, say editUser , instead of the selectedUser variable (which points to an element of your user collection). In your onUserSelected(event) , you'd initialize editUser via cloning the mutable properties of the selected user objects. Upon submitting the edit form ( (ngSubmit)="editSubmit()" ), you replace the original properties in the selected user object in the user collection.

    Something along the lines of:

    editUser: User = new User();
    selectedId: number;
    selectedUser: User;
    
    onUserSelected(event) {
        this.selectedId = event.data.id;
        this.selectedUser = this.users.filter(user => user.id === this.selectedId)[0];
        this.editUser = this.simpleClone(this.selectedUser);
    }
    
    editSubmit(event) {
        this.selectedUser = this.simpleClone(this.editUser);
    }
    
    simpleClone(obj: any) {
        return Object.assign({}, obj);
    }
    

    The simpleClone implementation is not suitable for deep cloning, so if your User objects hold references to other objects, this should be turned into a proper cloning function.

    链接地址: http://www.djcxy.com/p/6946.html

    上一篇: 如何克隆js对象?

    下一篇: 克隆对象TypeScript