Clean way to map objects to other objects?

大城市里の小女人 提交于 2019-12-01 19:29:56

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

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!