How Es6 rest and spread is working

2019-03-06 17:05发布

问题:

I now have the following code

var _ = require('underscore');
var raw =[
  {
    key :"name",value:"henry"
  },
  {
    key :"age",value:"old"
  },
  {
    key :"food",value:"matooke"
  },
  {
    key :"kids",value:"Acacia"
  },
  {
    key :"garbageA",value:"kasailoA"
  },
  {
    key :"garbageB",value:"kasasiroB"
  },

]
const endShape = _(raw)
.filter(({key}) =>!/garbage/.test(key))
.map(({key,value})=>({[key]:value}))
.reduce((acc,curr)=>({...curr, ...acc}));

console.log(endShape);

The code works well and I was following a tutorial. I understand up to the .map() method. Though I have failed to get a clear explanation of what

.reduce((acc,curr)=>({...curr, ...acc}));

is doing. How does is come up with this correct result ?

{ kids: 'Acacia', food: 'matooke', age: 'old', name: 'henry' }

回答1:

Basically, the map function outputs this:

[
  {
    name: 'henry'
  },
  {
    age: 'old'
  },
  {
    food: 'matooke'
  },
  {
    kids: 'Acacia'
  }
]

The reduce will then work like an Object.assign. It will iterate through the array above and add each key/value pairs to the accumulating object, which is an empty object at the start. That's why you get:

{ kids: 'Acacia', food: 'matooke', age: 'old', name: 'henry' }

The accumulation object is undefined at start but it doesn't matter thanks to the destructuring:

const foo = undefined;
const bar = { a: 'b' };

console.log({...foo, ...bar })