1

I have enum , that coming from back-end

Here is enum

    export enum InquiryStatus {
    _0 = 0, 
    _1 = 1, 
    _2 = 2, 
}

I create enum, to use in dropdown, like this

  export enum InquiryStatuses {
    Pending = InquiryStatus._0,
    Quoted = InquiryStatus._1,
    Lost = InquiryStatus._2,
}

And populate array, like this

filter: SelectItem[] = [];
     ngOnInit(): void {
        this.filter = [
            { label: 'Pending', value: InquiryStatuses.Pending },
            { label: 'Quoted', value: InquiryStatuses.Quoted },
            { label: 'Lost', value: InquiryStatuses.Lost },
        ];
    }

I need to make populating in function. I.E senв enum and name of array as parameters and return populated data to array. How I can do this correctly?

Eugene Sukh
  • 2,357
  • 4
  • 42
  • 86

2 Answers2

3

Since yurzui wrote a good answer, I'll just add how I was doing something similar.

export class EnumHelper {

    /** Returns array of objects based on enum values.
     *  Every object has text and value. 
     * Formats enum names if they are in pascal case.*/
    public static getTextAndValue(type: any, pascalCase: boolean = false): object[] {
        const result: Array<object> = [];
        for (var value in type) {
            if (Number.isInteger(type[value])) {
                result.push({ value: type[value], text: pascalCase ? value.replace(/([A-Z])/g, ' $1').trim() : value });
            }
        }
        return result;
    }
}
Matt
  • 308
  • 4
  • 10
2

The common way of doing this might be like this:

this.filter = Object.keys(InquiryStatuses)
                  .filter(k => typeof InquiryStatuses[k] === 'number')
                  .map(label => ({ label, value: InquiryStatuses[label] })))

Since Typescript "doubles" properties in enum when converting to object we have to filter it first.

yurzui
  • 205,937
  • 32
  • 433
  • 399