Search code examples
javascriptdestructuring

Is there a shortcut to destructure an object properties while keeping the object?


if I have a method signature as follows:

const myFunction = ({ property1, property2, property3 }) => ...

Is there a way I can also grab the parent object? Otherwise I have to write this:

const myFunction = myObject => {
   const { property1, property2, property3 } = myObject
}

Solution

  • In the example below you can access the x & y properties and cords itself, through destructuring:

    const drawCircle = ({cords, cords: {x,y},radius}) =>
      console.log(cords, x, y, radius)
    
    const circle = {
      cords: {
        x: 18,
        y: 30
      },
      radius: 50
    }
    
    drawCircle(circle)

    It's a bit unwieldy but you can get the entire object, by calling the function with:

    drawCircle({circle})

    and destructuring the object like so:

    ({circle, circle: {cords, cords: {x, y}, radius}})