简体   繁体   English

使用ES6解构简化javascript对象创建

[英]Simplify javascript object creation using ES6 destructuring

Is there a way to simplify the update of the user object using destructuring where I have an old object and I want to update to the new object with the same names for the properties. 有没有一种方法可以通过使用分解来简化用户对象的更新,其中我有一个旧对象,并且我想更新为具有相同名称的新对象。

I want to use the same user object and update the values rather than creating a new object. 我想使用相同的用户对象并更新值,而不是创建一个新对象。

function UpdateUserProps(user, updatedUser) {
    const { email, status } = updatedUser;
    user.email = email;
    user.status = status;
    return user;
}

You could use spread syntax ... in object. 您可以在对象中使用扩展语法... This creates a new object. 这将创建一个新对象。

 function UpdateUserProps(user, updatedUser) { return {...user, ...updatedUser} } 

You can also use parameter destructuring to take specific properties from update object. 您还可以使用参数解构从更新对象获取特定属性。

 function UpdateUserProps(user, {email, status}) { return {...user, ...{email, status}} } let user = { name: "foo", email: "foo", status: true } console.log(UpdateUserProps(user, { email: "bar", status: false })) 

You could do it without destructuring as well using Object.assign 您也可以使用Object.assign来完成,而无需破坏结构

function updateUserProps(user, updatedUser) {
 return Object.assign({}, user, updatedUser);
}

If you want to update in the same user object 如果要在同一用户对象中更新

function updateUserProps(user, updatedUser) {
 return Object.assign(user, updatedUser);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM