My code is as follows:
const defaultKeys = ["a", "b", "c"];
const defaultKeysObj = defaultKeys.reduce(
(acc: { [key: string]: number }, curr) => {
return (acc[curr] = 0), acc;
},
{}
);
What I'm trying to achieve is basically an object as such: {a: 0, b: 0, c: 0}
but I'm getting an error of unexpected use of comma operator. How can I modify my reduce
function?
CodePudding user response:
This should work the way you expect:
const defaultKeysObj = defaultKeys.reduce<{ [key: string]: number }>(
(acc, curr) => ({...acc, [curr]: 0}),
{}
);
You give return type in triangles, so called "generics", <{ [key: string]: number }> the type your returned result should be. And after each iteration you want to include all the previous values in the final result with spreading operator ...acc
and also include current value, so the object you want to return after each iteration is {...acc, [curr]: 0}
CodePudding user response:
When you use return (acc[curr] = 0), acc;
.
You can not returning own initialValue object so that accumulator is corrupted in second case. use console.log to view your accumulator
const defaultKeys = ["a", "b", "c"];
const obj = defaultKeys.reduce(
(acc, crr) => {
acc[crr] = 0;
return acc;
},
{}
);
console.log(obj);
Other way:
const defaultKeys = ["a", "b", "c"];
const keyMap = new Map();
for (const key of defaultKeys) keyMap.set(key, 0);
const obj = Object.fromEntries(keyMap);
console.log(obj);