use shorthand for object property assigment

Viewed 468

I'm using the following code

   function(props){

...
    this.props.appName = this.options.appName || this.props.appName;
          this.props.host = this.options.host || this.props.hos;
          this.props.endpoint = this.options.endpoint || this.props.endpoint;
          this.props.appPath = this.options.appPath || this.props.appPath;
    
       ....

Before I was using the or (||) I've used something like

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

I've many fields which I need to assign is there a way to make it shorter?

4 Answers

You can make use of spread operator here to unpack the values from other object, while keeping the first one as default.

var props={appName:'name', host:'host', appPath:'path'};

var options={appName:'UpdatedName', appPath:'pathUpdated'};

props = {...props, ...options};

console.log(props);

UPDATE

In case of undefine, I think you can iterate object using for..in loop, to settle the data:

var props={appName:'name', host:'host', appPath:'path'};

var options={appName:'UpdatedName', host:undefined, appPath:'pathUpdated'};

for(let item in options){
  if(options[item]) props[item] = options[item];
}

console.log(props);

Try the below

var props={appName:'name', host:'host', appPath:'path'};
var options={appName:'UpdatedName', appPath:'pathUpdated'};

props = Object.keys(props).reduce((target, key) => {
  target[key] = options[key] || props[key];
  return target;
}, {});
console.log(props);

You can do destruction:

  let {appName, host, endpoint, apPath} = this.props;
  let {appName: appNameOptions, host: hostOptions, endpoint: endpointOptions, apPath: appPathOptions} = this.options;

  appName = appNameOptions || appName;
  host = hostOptions || host;
  endpoint = endpointOptions || endpoint;
  appPath = appPathOptions || appPath;

As per your given snippet you just need to change the option in Object.assign().

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

This should be work for you.

Related