Search code examples
javascriptdestructuring

Destructuring an array and its properties at the same time


Is it possible to destructure elements of an array while also destructuring some of its properties as an object ?

For example, the following code compiles but doesn't give the expected result :

const array = [1, 2, 3]
array.myvalue = 'test'

function f([a, b, ...{ myvalue }]) {
  console.log(a, b, myvalue);
}

f(array)

Output :

1 2 undefined

Solution

  • You could take an object for destructuring with wanted indices and the named property.

    function f({ 0: a, 1: b, myvalue }) {
        console.log(a, b, myvalue);
    }
    
    const array = [1, 2, 3]
    
    array.myvalue = 'test'
    
    f(array)