I am trying to extract variables using object destructuring but those variables already exist, something like this
const x=1, y=2 // Those should be 1 and 2
const {x,y} = complexPoint
const point = {x,y}
Is there any way to do this without renaming the destructuring variables?.
Some like this and updating point avoiding const definition?
const point = {x,y} = complexPoint
The expected result should be as using object destructuring
const x=1, y=2 // Those should be 1 and 2
const point = {
x:complexPoint.x,
y:complexPoint.y
}
You can do this with array destructuring, i.e.:
const complexPoint = [1,2];
let x, y;
[x,y] = complexPoint;
As for object destructuring, an equivalent syntax would not work as it would throw off the interpreter:
const complexPoint = {x:1,y:2};
let x, y;
{x,y} = complexPoint; // THIS WOULD NOT WORK
A workaround could be:
const complexPoint = {x:1,y:2};
let x, y;
[x,y] = [complexPoint.x, complexPoint.y];
// Or
[x,y] = Object.values(complexPoint);
UPDATE:
It appears you can destructure an object into existing variables by wrapping the assignment in parenthesis and turning it into an expression. So this should work:
const complexPoint = {x:1,y:2};
let x, y;
({x,y} = complexPoint); // THIS WILL WORK
here it can be done like this.
const complexPoint = {x: 1, y: 2, z: 3};
const simplePoint = ({x, y}) => ({x, y});
const point = simplePoint(complexPoint);
console.log(point);
In a single line looks like this:
const complexPoint = {x: 1, y: 2, z: 3};
// can be written as
const point2 = (({x, y}) => ({x, y}))(complexPoint);
console.log(point2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With