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 );
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 );
You can use spread syntax ...
user = { ...body };
var body = { prop1 : "1", prop2 : "2", prop3 : "3" };
var user = { ...body };
console.log( user );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With