Search code examples
javascriptnode.jstypescriptlodash

JS merge two objects doesnt works


I try to use the following to merge object which doesn't works, what I need that if this.options have the property put it on this.props otherwise use the this.props defaults.

Any idea how I can merge it in a shorter way, I've more fields that are doing the same

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;

i've tried the following which doesnt works

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

and also this

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

Solution

  • Your first attempt, Object.assign(this.props, this.options) should work. If it doesn't that probably means that this.options has some falsy properties which you want to ignore. You can try filtering those out:

    const truthyOptions = Object.entries(this.options)
        .filter(([k,v]) => v)
        .map(([k, v]) => ({[k]: v}))
    
    this.props = Object.assign(this.props, ...truthyOptions)