Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
like image 386
user9145246 Avatar asked Dec 27 '17 13:12

user9145246


2 Answers

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 );
like image 141
gurvinder372 Avatar answered Sep 28 '22 23:09

gurvinder372


You can use spread syntax ...

user = { ...body };

var body = { prop1 : "1", prop2 : "2", prop3 : "3" };
var user = { ...body };
console.log( user );
like image 23
Jordi Castilla Avatar answered Sep 28 '22 23:09

Jordi Castilla