Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

js如何为对象指定属性快捷赋值?

场景:在web应用中做编辑功能的时候,往往会先调用一个详情接口,然后赋值给model,最后点击保存,但是我们编辑时往往可能属性很少,但是详情接口返回的数据比较多,如果我们通过Object.assign({}, this.formData, res) 来赋值,会导致 this.formData有很多不必要的属性,如果不这样赋值,就需要写很多代码为一个个属性赋值,有没有好一点的办法,既能够方便为对象属性赋值,又能不污染原始对象呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const result = {}
for(let key of Object.keys(this.formData)){
    result[key] = res[key] || this.formData[key];//(这里要注意深浅拷贝)
}
return result;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...