javascriptecmascript-6destructuringobject-destructuring

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
}

Solution

  • 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);