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' }
Basically, the
map
function outputs this:The
reduce
will then work like anObject.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:The accumulation object is
undefined
at start but it doesn't matter thanks to the destructuring: