Akshay Patil
Akshay Patil

Reputation: 621

Using spread notation in Array.reduce

I am trying to get the es6 syntax working for this code fragment.

let checkList = [1, 2].map(i => "Check " + i)

let checks = checkList
  // .reduce((acc, check) => Object.assign(acc, {[check]: {valid: false}}), {})
  .reduce((acc, check) => {...acc, {[check]: {valid: false}}}, {})
console.log(checks)

The output if i use the commented line in https://babeljs.io is as below and which is what i want to get using the new syntax.

Object {
  "Check 1": Object {
    "valid": false
  },
  "Check 2": Object {
    "valid": false
  }
}

I am not sure if there is a syntax error in this code. I tried selecting all the presets in babeljs but it does't compile properly.

Upvotes: 5

Views: 7519

Answers (2)

Estus Flask
Estus Flask

Reputation: 222840

Object spread is stage 4 proposal and isn't part of existing specifications. Stage 3 preset should be enabled in Babel, namely, transform-object-rest-spread.

There are syntax errors in the code above that will prevent it from being compiled properly even with required presets.

It should be

let checks = checkList
  .reduce((acc, check) => ({...acc, [check]: {valid: false}}), {});

Upvotes: 6

Sebass van Boxel
Sebass van Boxel

Reputation: 2602

First of all you don't have wrap the properties in an extra object (unless you also want to use the spread operator on that).

So {...acc, {[check]: {valid: false}}} can become {...acc, [check]: {valid: false}}

This means you're adding an object to accumulator. The key of this object is the name you assigned it (Check[n]) and the values are the ones you set ({valid...}).

Secondly, as far I know, you cannot use the spread operator without explicitly a new value. So you should either write your state on a new line like:

let checks = checkList.reduce((acc, check) => {
  return {...acc, [check]: {valid: false}}
}, {})

Or wrap it in extra parentheses:

let checks = checkList.reduce((acc, check) => ({...acc, [check]: {valid: false}}) , {})

Upvotes: 5

Related Questions