Clean way to map objects to other objects?

后端 未结 2 436
深忆病人
深忆病人 2021-01-19 06:47

Is there a good way to map objects to other objects? Library recommendations welcome too.

For example, say I have these classes:

export class Draft {         


        
2条回答
  •  感情败类
    2021-01-19 07:22

    With regards to copying properties of the same name, you can use Object.assign:

    fromDraft(Draft draft) {
        Object.assign(this, draft);
        this.info = new Info();
        this.info.value = draft.summary;
    }
    

    The problem is that it will also create this.summary, but it's a convenient way of copying properties so if you can model your classes differently then you can use it.

    Another option is to have a list of shared property names and then iterate it:

    const SHARED_NAMES = ["id", "name"];
    
    fromDraft(Draft draft) {
        SHARED_NAMES.forEach(name => this[name] = draft[name]);
        this.info = new Info();
        this.info.value = draft.summary;
    }
    

提交回复
热议问题