1

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
5
  • What is the expected output? Commented Feb 21, 2020 at 9:02
  • 2
    @mplungjan I suppose 1 2 "test" Commented Feb 21, 2020 at 9:03
  • @Strebler what about this syntax ? jsfiddle.net/u72wfcra I know it doesn't give "exactly" what you want x) Commented Feb 21, 2020 at 9:10
  • @IslamElshobokshy This does not work. You just collect the remaining part of the array. Commented Feb 21, 2020 at 9:12
  • @Strebler yeah yeah fine :P Commented Feb 21, 2020 at 9:13

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, I have actually thought of that, but I was wondering if there was a syntax where we can also benefit from the classic array destructuring syntax. If there's nothing better, I'll mark this answer as accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.