3

I am trying to use the Object Spread syntax like so:

let credentialsWithAuth =  { ...credentials, type: 'basic' }

Where credentials is an object with username and password as keys and values. But this blows up with SyntaxError: Unexpected token ...

So do I have to setup node with babel for this to work? I thought native support was now built in.

http://node.green/

Can't I use this without Object.assign etc?

Could someone please clarify?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Amit Erandole
  • 11,995
  • 23
  • 65
  • 103
  • Is this suppose to work on vanilla Node without Babel? – JohnnyQ Jan 28 '17 at 13:52
  • Yeah that's what I am wondering after looking at this http://node.green/ – Amit Erandole Jan 28 '17 at 13:53
  • 2
    According to [this](http://stackoverflow.com/a/36666473/3889043) answer, the Object spread is not an official implementation of ECMAscript, yet. Only works array spread. This, for instance, would work: `credentials = [1,2]; [...credentials, 3]`. You'll have to go with `babel` or `Object.assign`, unfortunately. – mrlew Jan 28 '17 at 14:01
  • **Note that the spread operator can be applied only to iterable objects:** from msdn – Karan Garg Jan 28 '17 at 14:03

2 Answers2

3

Spread syntax which is available in node 7.0 doesn't handle spreading properties of an object. What you're looking for is object spread syntax which is currently on stage 3 of TC39 Process. You can find more info about the process in the process document and info about proposal in its repository.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Bartosz Gościński
  • 1,468
  • 1
  • 16
  • 28
  • Old question, but just wanted to update that node v8+ has full support for object spread. Here's the non-esnext support link https://kangax.github.io/compat-table/es2016plus/#test-object_rest/spread_properties – wspurgin Jul 27 '18 at 18:34
0

Yes, it is only supported in node_8x and above. However the correct equivalent using Object.assign() (That does not overwrite the source object) is:

let credentials = { username : 'test', password: 'test' }
let credentialsWithAuth = Object.assign({}, { type: 'basic' }, credentials)

console.log(credentialsWithAuth)
Mohamed Sohail
  • 1,659
  • 12
  • 23