3

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
}
Juan Caicedo
  • 1,144
  • 16
  • 24

3 Answers3

6

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
Gabor Szekely
  • 938
  • 3
  • 11
3

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);
Bibberty
  • 4,282
  • 1
  • 6
  • 22
1

It's not 100% clear to me what you want to do.

If you want to update point with two properties of complexPoint

You can actually destructure an object into anything that is assignable. Most often you will destructure into variables, but you can also destructure into properties.

Example:

const point = {x: 1, y: 2};
const otherPoint = {x:3, y: 4};

   ({x: point.x, y: point.y} = otherPoint);
// ^                                     ^
// parenthesis are necessary otherwise the runtime will interpret {
// as the start of a block

console.log(point);

Of course this can become difficult to read the more properties you have. You can also just assign them directly, the good old fashioned way:

point.x = otherPoint.x;
point.y = otherPoint.y;

Or with a loop:

for (const prop of ['x','y']) {
  point[prop] = otherPoint[prop];
}

If you want to create a new object from an existing object

Create a helper function to "pick" the properties from the existing object. Such a function is provided here.

const point = pick(otherPoint, 'x', 'y');
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072