Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6: change a value while destructuring

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
like image 788
delp Avatar asked Apr 01 '26 13:04

delp


1 Answers

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)
like image 141
Ori Drori Avatar answered Apr 08 '26 19:04

Ori Drori



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!