首页 > 解决方案 > JS合并两个对象不起作用

问题描述

我尝试使用以下内容来合并不起作用的对象,如果this.options将属性放在上面,我需要什么,this.props否则使用this.props默认值。

知道如何以更短的方式合并它,我有更多的字段在做同样的事情

this.props!.hostName = this.options.hostName || this.props!.hostName;
this.props!.eventType = this.options.eventType || this.props!.eventType;
this.props!.eventTypeVersion = this.options.eventTypeVersion || this.props!.eventTypeVersion;
this.props!.uri = this.options.uri || this.props!.uri;

我已经尝试了以下不起作用

this.props = Object.assign(this.props, this.options);

还有这个

this.props = Object.assign(this.options, this.props);

标签: javascriptnode.jstypescriptlodash

解决方案


使用扩展运算符:

{...props, ...options}

或者

for (const [k, v] of Object.entries(props)) {
  props[k] = options[k] || v
};

推荐阅读