Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 509
Akshay Patil Avatar asked Jun 21 '17 18:06

Akshay Patil


1 Answers

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}}), {});
like image 115
Estus Flask Avatar answered Sep 21 '22 08:09

Estus Flask