0

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?

5
  • obj[user.name] seems to create a property on obj with the name user.name and then assigns it the value user.age. Commented Apr 28, 2021 at 9:15
  • 2
    If you expect the result to be { John: 34, ... }, then surely you must set the key to the name and its value to the age…?! Commented Apr 28, 2021 at 9:15
  • 1
    Try const u = {}; u['John'] = 34; console.log(u);…? Commented Apr 28, 2021 at 9:17
  • @deceze, you seem to be able to point out some of my confusion: const u = {}; u['John'] = 34; console.log(u); works perfectly fine while doing this in one go {}['John'] = 34 throws an error. Commented Apr 28, 2021 at 9:24
  • That's just a bad test because the meaning of {} is ambiguous here. ({}['John']) = 34 would 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. Commented Apr 28, 2021 at 9:25

1 Answer 1

1

In essence, the flow you're describing is what's happening, but it's not valid JS, the way it was written.

If I tweak the code a bit into valid JS, this is what you get:

//**ITERATION 1:**
let accumulator = {};
console.log('Accumulator:\n', accumulator);

let currVal = {name: 'John', age: 34};
console.log('Current value:\n', currVal);

accumulator[currVal.name] = currVal.age;
console.log('Updated accumulator:\n', accumulator)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.