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);
The console would display the value { John: 34, Amy: 20, camperCat: 10 }
.
Please explain me this code
what does confuse you?
what parts do you understand? what parts do you not understand?
how that reduce method return object = { John: 34, Amy: 20, camperCat: 10 }.
and working of these few lines = { obj[user.name] = user.age;
return obj;
}, {})
what the reeuce method returtn depends on what is returned by its callback, in this case obj
, which is an object (as the starting value of the accumulator is {}
)
then for each element in the array a new property is added to the object with
but
when I put = console.log({}[users[0].name] = users[0].age); //34
it doesn’t give object
What do you think this line should do?
const users = [
{ name: ‘John’, age: 34 },
{ name: ‘Amy’, age: 20 },
{ name: ‘camperCat’, age: 10 }
];
console.log({}[users[0].name] = users[0].age) should give //John: 34
according to :-
const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
No.
This line is modifying obj inside of a reduce.
On this line, I’m not sure what the {} is doing, but the rest is assigning user 0’s age as user 0’s name. I’d guess that it logs 34.
How familiar are you with what reduce does? That reduce is returning obj after the callback function is called for every element in the users array.
let obj = {};
obj[users[0].name] = users[0].age
console.log(obj)
please can you suggest me some topic to review so that I can feel this code more deeply
it’s object manipulation, nothing fancy or weird
1 Like
system
Closed
September 11, 2021, 8:51pm
13
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.