0

For some unknown reason, I can't get object spread to work in my code. I'm having to fall back on 'Object.assign()', but would rather use '...'

The following works:

const frederick = {
  name: 'Frederick Douglass',
  canRead: false,
  canWrite: false
};

// create new object and mutate that one
const selfEducate = person =>
  Object.assign({}, person,
    {canRead:true},
    {canWrite:true}
  );

console.log(selfEducate(frederick));  // { name: 'Frederick Douglass', canRead: true, canWrite: true }
console.log(frederick);  // { name: 'Frederick Douglass', canRead: false, canWrite: false }

However, the following does not:

const frederick = {
  name: 'Frederick Douglass',
  canRead: false,
  canWrite: false
};

const selfEducate = person =>
  ({
    ...person,
    canRead: true,
    canWrite: true
  });

console.log(selfEducate(frederick));
console.log(frederick);

That one errors out with:

SyntaxError: Unexpected token ...

The spread operator does work in other code of mine that involves copying arrays, but not in this example. Any feedback would be appreciated.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ron Allen Smith
  • 603
  • 2
  • 7
  • 19
  • 3
    In object literals, it's an upcoming feature (most likely) and isn't supported in most implementations. http://kangax.github.io/compat-table/esnext/#test-object_spread_properties –  May 12 '17 at 02:19
  • At which browser are you trying `javascript` at Question? – guest271314 May 12 '17 at 02:26
  • 1
    ES7 on this is a misnomer. ES7 is out and done, and ES8 is _almost_ out and done. Object spread like this is still a proposal, though it could end up in ES9. – loganfsmyth May 12 '17 at 02:30
  • @loganfsmyth: That's why I prefer using ES20XX to refer to recent versions (i.e. ES2016, ES2017). – Felix Kling May 13 '17 at 07:28
  • 2
    [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling May 13 '17 at 07:29

2 Answers2

1

If your other parts of code are working with the spread operator against arrays, that's not the same as trying to spread an object literal.

There's proposals for the spec to have it, such as here.

mariocatch
  • 8,305
  • 8
  • 50
  • 71
0

Please try the following steps.

Installation

npm install --save-dev babel-plugin-transform-object-rest-spread

Usage in existing presets

"plugins": ["transform-object-rest-spread"]

Reference link: Click here

NB: The object spread operator is not a default feature. It requires transpiler as above.

supriyar
  • 1
  • 1