1

I just wonder why when I am trying to return an object when I do immediately assigning some value to it the result is not as I expected and the lamda function doesn't return me an object but the value.

To clarify my question here is code:

1) Wrong variant ( but I want to use something like that because it's a lil bit shortest)

const a = {
 "a" : "a",
 "b" : "b",
 "c" : "c"
}

const res = Object.keys(a).reduce((res, key) => ( res[key] = 0 ), {});
console.log(res) // result -> 0; but why, does it return an assigning value in that case?

2 variant (correct but a little bit longest)

const a = {
 "a" : "a",
 "b" : "b",
 "c" : "c"
}

const res = Object.keys(a).reduce((res, key) => { res[key] = 0; return res; }, {});
console.log(res); // { "a" : 0, "b" : 0, "c" : 0 }. It works properly now!

Can someone help me, please, to understand this moment? I belive that it's a little bit stupid question but anyway I'll be very appreciate for any information. Thanks!

Velidan
  • 4,657
  • 9
  • 39
  • 75
  • A common idiom is to return `Object.assign`, see https://stackoverflow.com/questions/42974735/create-object-from-array – georg Oct 25 '17 at 14:06

1 Answers1

6

Assignments, such as res[key] = 0 return the assigned value - 0. You need to return res. You can use the comma operator to return the last value (res):

const a = {
 "a" : "a",
 "b" : "b",
 "c" : "c"
}

const res = Object.keys(a).reduce((res, key) => (res[key] = 0, res), {});
console.log(res)
Ori Drori
  • 166,183
  • 27
  • 198
  • 186