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?

3
  • "I need to make populating in function" Your requirement is not clear. Commented Jun 11, 2019 at 13:59
  • I edited question @AvinKavish Commented Jun 11, 2019 at 14:02
  • How to get names of enum entries? Commented Jun 11, 2019 at 14:05

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.