2

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.

naspy971
  • 1,137
  • 2
  • 13
  • 31
  • 1. Create a function. 2. Reuse it. 3. Done - it's short and simple anywhere you use it.\ – VLAZ Dec 24 '21 at 07:57
  • 1
    What you really want is to **not** destructure. Simply don't use destructuring – slebetman Dec 24 '21 at 08:09
  • If you're using lodash, `_.pick(decodeToken(token), ['email', 'firstname', 'lastname', 'isAdmin'])` will do the trick. – harttle Dec 24 '21 at 08:11
  • You cannot avoid typing the variable names twice, without using helper functions. If the "*problem*" is the two lines, although i cannot see why that would be, you can use `const {email, firstname, lastname, isAdmin, user={email, firstname, lastname, isAdmin}} = decodeToken();` but i post this only as a technical solution. Not one that should be really used. The two lines you have are just fine and clear to understand. – Gabriele Petrioli Dec 24 '21 at 09:08

1 Answers1

2

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);
Mario Santini
  • 2,905
  • 2
  • 20
  • 27