How obj[] = user.age; works


I can’t figure out how

obj[] = user.age;

from the callback function is working there. The = sign is an assignment, shouldn’t we have a += operator to add the value of user.age to obj[] instead ?
Sorry in advance if you find my question silly, but it’s important for me to understand each steps of the program.
Thank you! :slightly_smiling_face:

const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }

const usersObj = users.reduce((obj, user) => {
  obj[] = user.age;
  return obj;
}, {});

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

The way I understand this, is that you’re creating a new object ‘usersObj’ and filling with elements with new keys set to the names of the ‘users’ object, and assigning the new values to the values of the ‘age’ keys from the ‘users’ object.

also your snippet has “obj[user.age] = user.age” when I think it should be obj[] = user.age

hope this helps! :smile:

Thank for answering,

yeah my bad, I tried to manipulate the object earlier to try to understand how it works and I forgot to reset the code :sweat_smile: sorry

yeah now I got it, the obj element is an accumulator to store the variable all along the iteration.

Thank you ! :slightly_smiling_face:

1 Like