2

for example

 state = { 
      "username": "abc",
      "id": "1",
 } 


 const {username, id} = this.state

the above code would work and get the values

is there a way to make it so below would also work

const {user, userId} = this.state

That is, get the same values as username, id but with different names. Any way to tell javascript that user means username and userId means id?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
name
  • 235
  • 2
  • 12
  • I don't know if you are referring to alias, if so, you can do it like this `const {username:user, id: userId} = this.state;` then you can use `user` and `userId` in your code – ludwiguer Jul 01 '20 at 22:27
  • See **[THIS](https://codeburst.io/renaming-destructured-variables-in-es6-807549754972)** guide from codeburst. It explains what are you looking for :) – Carlo Corradini Jul 01 '20 at 22:28

3 Answers3

1

You can do like this if you just want to use different names:

const {username: user, id: userId} = this.state
Talmacel Marian Silviu
  • 1,596
  • 2
  • 6
  • 14
1

Yes you can do it like this:

const {username: user, id: userId} = this.state

Great docs here https://javascript.info/destructuring-assignment

Grant Singleton
  • 1,611
  • 6
  • 17
0

Assigning to new variable names:

const o = {p: 42, q: true};
const {p: foo, q: bar} = o;
 
console.log(foo); // 42 
console.log(bar); // true

More information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Yaroslav
  • 110
  • 4