Skip to content
Advertisement

How to create initial value for .reduce based on enum?

I have a reduced function that needs initial values based on an enum. See simplified code below:

items.reduce<Record<RoleType, Community[]>>(
    (acc, community) => {
        ... // this works
    },
    { [RoleType.LEADER]: [], [RoleType.FACILITATOR]: [], [RoleType.EDITOR]: [], [RoleType.EXPERT]: [], [RoleType.MEMBER]: [] }
);

The enum looks like this:

export enum RoleType {
    EXPERT = 'EXPERT',
    LEADER = 'LEADER',
    FACILITATOR = 'FACILITATOR',
    EDITOR = 'EDITOR',
    MEMBER = 'MEMBER'
}

I don’t want to explicitely list every member of the enum though. I tried with the following:

{ ...Object.values(RoleType).map((role) => ({ [role]: [] })) }

Is there a way to simply add empty arrays for all of the enum’s members? Best case would be if there was proper typing too.

My attempt above throws this error (which I really don’t know what to do with):

Type ‘{ [n: number]: { [x: string]: any[]; }; length: number; toString(): string; toLocaleString(): string; pop(): { [x: string]: any[]; }; push(…items: { [x: string]: any[]; }[]): number; concat(…items: ConcatArray<{ [x: string]: any[]; }>[]): { …; }[]; concat(…items: ({ …; } | ConcatArray<…>)[]): { …; }[];…’ is missing the following properties from type ‘Record<RoleType, Community[]>’: EXPERT, LEADER, FACILITATOR, EDITOR, MEMBER

Answer

{ ...Object.values(RoleType).map((role) => ({ [role]: [] })) }

will create an object with indices of the array as key.

{
  "0": { "EXPERT": [] },
  "1": { "LEADER": [] },
  "2": { "FACILITATOR": [] }
  ...
}

You need to use something like this:

Object.assign({}, ...Object.values(RoleType).map(r => ({ [r]: [] })))
Advertisement