gpt4 book ai didi

javascript - 使用对象属性分配的简写

转载 作者:行者123 更新时间:2023-12-01 15:42:04 25 4
gpt4 key购买 nike

我正在使用以下代码

   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);我有很多需要分配的字段有没有办法让它更短?

最佳答案

您可以使用spread operator此处从其他对象中解压缩值,同时将第一个对象保留为默认值。

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

关于javascript - 使用对象属性分配的简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62495265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com