使用对象属性分配的速记方式

4

我正在使用以下代码

   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;
    
       ....

在使用逻辑运算符or(||)之前,我使用了类似于下面的代码:

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

我有很多需要赋值的字段,有没有更短的方法?


这个怎么样:this.props = {...this.props, ...this.options} - gorak
1
你为什么放弃了使用 Object.assign 的方式? - Oboo Cheng
这个回答解决了你的问题吗?如何动态合并两个JavaScript对象的属性? - user120242
似乎存在潜在的错误,因为0""false的值也将被替换。 - Slai
4个回答

1
你可以在这里使用 扩展运算符 来解包其他对象中的值,同时保留第一个对象作为默认值。

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

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

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

console.log(props);

更新

如果出现未定义情况,我认为您可以使用for..in循环迭代对象来解决数据:

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);


如果 options 持有一个 falsy 属性(例如 undefined),|| 运算符将会保留 props 属性,而在这里你正在将该 falsy 属性设置为 props。 - grodzi
但是如果“options”未定义,循环将不会启动。 - Beno Odr

1
尝试以下内容:

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);


谢谢,我在使用TypeScript时遇到了target[key]的错误,报错信息为TS7053: 元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型'{}'。在类型'{}'上找不到带有参数类型为'string'的索引签名。 你有什么解决方法吗? - Beno Odr
我在TypeScript上尝试了同样的操作,运行良好。有特定的框架吗? - Girish Sasidharan
不,只是使用与WebStorm集成的“eslint推荐”工具。 - Beno Odr
尝试在Angular 6上进行相同的操作-> https://stackblitz.com/edit/copytaskshorthand,Typescript -> https://jsfiddle.net/boilerplate/typescript - Girish Sasidharan

0
你可以进行破坏:
  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;

0
根据您提供的片段,您只需要更改Object.assign()中的选项。
this.props = Object.assign(this.props, this.options);

这对你来说应该可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接