9

Lets say I have an object

const obj = { width: 100, height: 200 }

I wish to pass that object to a method

myFunc( obj );

Inside that method I wish to pull out the height, but at the same time subtract a value. I only wish to do this once and after that it will never change.

Doing the following will get me the correct height I want of say 150.

let {height: localHeight} = obj;
localHeight = localHeight - 50;

How do I do the above in a single line ? Something like this - but I know this doesn't work.

const { height: (localHeight = localHeight - 50) } = obj
mklement0
  • 382,024
  • 64
  • 607
  • 775
delp
  • 771
  • 11
  • 20
  • 1
    I think this link might give you some help http://exploringjs.com/es6/ch_destructuring.html#sec_default-values-destructuring – utsav Jan 24 '19 at 11:23
  • 1
    related: [Javascript ES6+: Destructuring and using an array method at the same time?](https://stackoverflow.com/q/49571990/1048572) – Bergi Jan 24 '19 at 11:40

2 Answers2

7

It's possible, although it's a hack that hurts readability, might produce an error (if the object will contain the fake property in the future), and shouldn't be used in a real product.

You can destructure a non existing property, and use the default value to do the subtraction.

const obj = { width: 100, height: 200 }

const { height, localHeight = height - 50 } = obj

console.log(localHeight)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Just don't do destructuring then and instead write the one-liner `const {height} = obj, localHeight = height - 50;`. Same number or characters, but works as expected. – Bergi Jan 24 '19 at 11:45
  • Thanks, I get that its a hack from the above and my use case isn't quite as simple as the question - but the answer is a good one and clearly warns me from using it :) – delp Jan 24 '19 at 11:56
4

No, this is not possible. Destructuring does just that, it assigns properties to target expressions. Assignment syntax does not have any modifiers for altering the assigned value (default initialisers are already a stretch).

Just don't use destructuring and you get to do it in a single statement:

const localHeight = obj.height - 50;

Much shorter and less complicated than anything you could achieve with destructuring.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375