将对象映射到其他对象的干净方法? [英] Clean way to map objects to other objects?

查看:76
本文介绍了将对象映射到其他对象的干净方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在将对象映射到其他对象的好方法?图书馆的建议也欢迎。



例如,说我有以下课程:

  export class Draft {
id:number;
名称:字符串;
摘要:字符串;
}

出口分类书{
id:number;
名称:字符串;
info:信息;
}

出口分类Info {
value:string;
}

传统上,要映射 Draft Book 我必须手动为每个字段这样做:

  export class Book {
[...]

fromDraft(草稿草案){
this.id = draft.id;
this.name = draft.name;
this.info = new Info();
this.info.value = draft.summary;
}
}

是否有更简便的方法来映射对象字段命名方式相同吗?例如草稿 Book id name 字段,同时还可以定义自定义映射,例如从 draft.summary book。 info.value



请注意,这与我的实际用例相去甚远。在这里,手动进行分配并不是很糟糕,但是对于具有许多类似命名字段的对象来说,这是一件很麻烦的事情。



谢谢!

解决方案

不管TypeScript是什么,您都可以使用lodash _。mergeWith 并传递合并功能。



优点:更通用(如果您有更多逻辑,可以添加它(例如,对于复杂类型)



缺点:您需要lodash



类似的东西:



< pre class = snippet-code-js lang-js prettyprint-override> var a = {foo:[1,2,3],bar:true} var b = {foo:[4, 5,6,7],bar:false} var c = _.mergeWith(a,b,function(a,b){if(a.concat){return a.concat(b);} else {return b; }})console.log('c',c);

 < script src = https://cdn.jsdelivr.net/lodash/4/lodash.min.js>< / script>  



http://jsbin.com/xugujon/edit?html,js


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 {
    id: number;
    name: string;
    summary: string;
}

export class Book {
    id: number;
    name: string;
    info: Info;
}

export class Info {
    value: string;
}

Traditionally, to map fields from Draft to Book I'd have to do so manually for each field:

export class Book {
    [...]

    fromDraft(Draft draft) {
        this.id = draft.id;
        this.name = draft.name;
        this.info = new Info();
        this.info.value = draft.summary;
    }
}

Is there an easier way to map object fields that are named the same way? For example Draft and Book's id and name fields, while also being able to define custom mappings, like from draft.summary to book.info.value.

Note that this is far from my actual use case. Here it's not so bad to do assignments manually, but for objects with many similarly named fields it's quite a chore.

Thanks!

解决方案

Regardless of TypeScript, you can use lodash _.mergeWith and pass your merge function.

Advantage: More generic (If you have more logic you can add it (for complex types for example)

Disadvantage: You need lodash

Something like:

var a = {
  foo: [1, 2, 3],
  bar: true
}

var b = {
  foo: [4, 5, 6, 7],
  bar: false
}

var c = _.mergeWith(a, b, function(a, b) {
  if (a.concat) {
    return a.concat(b);
  }
  else {
    return b;
  }
})

console.log('c', c);

<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>

http://jsbin.com/xugujon/edit?html,js

这篇关于将对象映射到其他对象的干净方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆