Search code examples
javascriptnode.jsecmascript-6ecmascript-5ecmascript-2016

Best way to handle multiple assignment of the same property in javascript


This is the situation:

user.username = body.username;
user.name = body.name;
user.surname = body.surname;
user.email = body.email;
user.password = body.password;
user.privilege = body.privilege;
user.pin = body.pin;
user.rfidTag = body.rfidTag;

I modified it this way and it works as expected:

for (let propt in body) { 
    user[propt] = body[propt];
}

I am wondering if there is a more elegant way to write this, maybe something that has a property check.

[UPDATE]: There are various ways to solve this.

If you don't need to retain user properties:

user = Object.assign( {}, body );

or the proposal spread property:

user = { ...body };

Otherwise to retain properties of user:

Object.assign( user, body );

Solution

  • You can use Object.assign

    user = Object.assign( {}, body );
    

    Demo

    var body = { user : "abc", username : "some-value" };
    
    var user = Object.assign( {}, body );
    
    console.log( user );

    Edit

    If user already has some properties (which are not in body) which you don't want to be wiped-off then

    Object.assign( user, body );