简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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