0

Given the following example, why can't I use a combination of spread with deconstructing assignment?

let myObj = {
  one: 1,
  two: 2,
  three: 3,
}

let {...Object.keys(myObj)} = myObj;

console.log(one);

Desired result: 1

Actual result: Uncaught SyntaxError: Unexpected token ...

EDIT: Breaking out the above so that the function execution is separate makes no difference:

let obj2Array = Object.keys(myObj);

let {...obj2Array} = myObj;

Still results in SyntaxError: Unexpected token ...

Dan Mandle
  • 5,608
  • 3
  • 23
  • 26
  • 3
    Apart from spread syntax only being available for arrays in ES6, how do you want to assign to `Object.keys(myObj)`?! That's a function call, not an identifier. – Bergi Jan 09 '17 at 15:51
  • A function call can't be part of a destructuring assignment target. – Pointy Jan 09 '17 at 15:52
  • 1
    This is essentially variable variables, which Javascript never supported. For good reason, because it's a bad idea. – deceze Jan 09 '17 at 15:52
  • This seems to be an XY problem. Your actual question would be a duplicate of [Is it possible to import variables in JavaScript (node.js)?](http://stackoverflow.com/q/21562973/1048572) I guess – Bergi Jan 09 '17 at 15:54
  • 1
    `...x` already has a meaning in destructuring assignments. It is used to indicate that all the remaining elements (or properties in case of the object *rest* property proposal) should be assigned to that variable. It's a *rest* element/property, basically the opposite of *spread*. It cannot have two different behaviors at once. – Felix Kling Jan 09 '17 at 16:06
  • @Bergi, Object.keys() returns an array. I'm trying to spread the resulting array. – Dan Mandle Jan 09 '17 at 20:19
  • You are misunderstanding how [spread syntax](http://stackoverflow.com/a/37152508/1048572) works. You can only spread something into an array literal or an argument list (and there's a proposal to spread into object literals). In destructuring, you create an array (or object) that is filled with the rest of the values. You never get to use spread with multiple variables, and you definitely don't get to choose them dynamically. Take @deceze's comment to heart. – Bergi Jan 09 '17 at 21:47

0 Answers0