On FreeCodeCamp, I was introduced to this snippet of code:
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
console.log(usersObj);
// expected result : { John: 34, Amy: 20, camperCat: 10 }
I've been looking at this for a while now and just can't wrap my head around how the reduce function works here. In my view it works as follows in the first iteration:
**ITERATION 1:**
Initial Accumulator (obj): {}
CurrVal (user): {name: 'John', age: 34}
Updated Accumulator: {}[{name: 'John', age: 34}.name] = {name: 'John', age: 34}.age;
But immediately there, it goes wrong in my console when trying this step by step, as I understand the Updated Accumulator is basically saying ["John"] = 34 Why are we setting the name equal to the age?
What am I missing here to connect the missing pieces? Why does the above code work?
obj[user.name]seems to create a property onobjwith the nameuser.nameand then assigns it the valueuser.age.{ John: 34, ... }, then surely you must set the key to the name and its value to the age…?!const u = {}; u['John'] = 34; console.log(u);…?const u = {}; u['John'] = 34; console.log(u);works perfectly fine while doing this in one go{}['John'] = 34throws an error.{}is ambiguous here.({}['John']) = 34would do, but the result will be discarded immediately because the object you're creating on the fly here isn't assigned to anything, so you won't see the resulting object.