Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to destructure an object into existing variables?

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
}
like image 624
Juan Caicedo Avatar asked Nov 20 '25 21:11

Juan Caicedo


2 Answers

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
like image 83
Gabor Szekely Avatar answered Nov 23 '25 10:11

Gabor Szekely


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);
like image 26
Bibberty Avatar answered Nov 23 '25 11:11

Bibberty



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!