[英]How Es6 rest and spread is working
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.
我了解.map()方法。 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' }
Basically, the map
function outputs this: 基本上,
map
函数输出以下内容:
[
{
name: 'henry'
},
{
age: 'old'
},
{
food: 'matooke'
},
{
kids: 'Acacia'
}
]
The reduce
will then work like an Object.assign
. 然后
reduce
将像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: 累积对象在开始时是
undefined
,但是由于解构的关系并不重要:
const foo = undefined; const bar = { a: 'b' }; console.log({...foo, ...bar })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.