1

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);
Magiczne
  • 1,586
  • 2
  • 15
  • 23
PJEM
  • 557
  • 7
  • 33

2 Answers2

1

Use spread operator:

{...props, ...options}

OR

for (const [k, v] of Object.entries(props)) {
  props[k] = options[k] || v
};
V.Tur
  • 1,115
  • 9
  • 20
1

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)
ccarton
  • 3,556
  • 16
  • 17