Home » Javascript » javascript – Destructuring an array and its properties at the same time

javascript – Destructuring an array and its properties at the same time

Posted by: admin February 23, 2020 Leave a comment

Questions:

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
How to&Answers:

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)