Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in JS to assign in one line destructured object keys to another object? [duplicate]

My question is really simple but I have not been able to find an answer to this.

Currently I have this :

const {email, firstname, lastname, isAdmin} = decodeToken(token);
const user = {email, firstname, lastname, isAdmin};

I'm looking for a way to shorten this chunk of code into a single line. I tried different combinations but none worked.

like image 408
naspy971 Avatar asked Dec 21 '25 08:12

naspy971


1 Answers

I think you can simply write:

const user = {email, firstname, lastname, isAdmin} = decodeToken(token);

So you can have the user object and the destructured fields accessible as variables in the scope.

UPDATE

This code as to be considered careful as @VLAZ pointed out in the comment, the destructured variables now are global. You can still avvoid this but you cannot have it in a single line as you requested:

let email, firstname, lastname, isAdmin;
const user = {email, firstname, lastname, isAdmin} = decodeToken(token);

If you don't need the destructured fields you can shorten even more:

const user = decodeToken(token);
like image 148
Mario Santini Avatar answered Dec 22 '25 21:12

Mario Santini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!