1

Can I build object on the fly using deconsturct? Like I token is under this.request.body.token, how can I get the value and assign it to a object property? Tried below example it won't work:

const params = {
    token
} = this.request.body

console.log(params.token) //undefined

I have to do this

const reqBody = this.request.body

const params = {
  token: reqBody.token
}

console.log(params.token) //123
  • Possible duplicate of [ES2015 deconstructing into an object](https://stackoverflow.com/questions/35157549/es2015-deconstructing-into-an-object) – str May 08 '18 at 07:09

2 Answers2

0

Use a colon while destructuring to assign to a standalone variable with a different name than the property name:

const obj = { request: { body: { token: 'abc' } } };
// obj is equivalent to the `this` in your code

const { request: { body: reqBody } } = obj;
console.log(reqBody);

If you're OK with the variable name being just body, then it's even easier:

const obj = { request: { body: { token: 'abc' } } };
// obj is equivalent to the `this` in your code

const { request: { body } } = obj;
console.log(body);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I think I'll just stick to my old way this is so unreadable, btw thanks for the answer! –  May 08 '18 at 07:26
  • Learning the new concise syntax is a *good* thing - don't be afraid of using it, it has its place. – CertainPerformance May 08 '18 at 07:29
  • 1
    Neither are arrow functions, the first time you come across them, nor are `for` loops, nor are many other syntax constructs, but don't let that stop you from learning them - they're useful, and once you know them, you'll use them whenever appropriate, and be happier as a result. – CertainPerformance May 08 '18 at 07:39
0

If the object you are destructuring has a few standard properties, you can do this by omission using object rest:

const thisRequestBody = {
  a: 'a', 
  b: 'b',
  token: 'token'
}

const { a, b, ...params } = thisRequestBody;

console.log(params);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209