mcilhaggis
mcilhaggis

Reputation: 55

How to get index value of choice made with Inquirer?

I'm trying to get an integer value from the user when this questions is asked:

        let q4 = {
        type: 'list',
        name: 'manager',
        message: 'Who do they report to?',
        choices: ['Jen','Rachel','Tania']
    };

let answerProcessing = (answer) => {
     console.log(answer.manager)
            }

but I can't figure it out from the documentation and I don't see any similar questions to this one. Perhaps it's really obvious but I can't get a non-string response.

Upvotes: 1

Views: 2025

Answers (2)

Aleksandar
Aleksandar

Reputation: 1766

You can give your choices a name and value. The name will be output in the terminal. The value can be whatever simple value you like it to be, like a number, or a short for the name.

let q4 = {
    type: 'list',
    name: 'manager',
    message: 'Who do they report to?',
    choices: [
        {
            name: 'Jen',
            value: 1,
        },
        {
            name: 'Rachel',
            value: 2,
        },
        {
            name: 'Tania',
            value: 3,
        }
    ]
};

let answerProcessing = (answer) => {
    console.log(answer.manager)  // outputs 1, 2, or 3
}

Upvotes: 4

mcilhaggis
mcilhaggis

Reputation: 55

Figured it out:

console.log(q4.choices.indexOf(answer.role));

This will give the index value. Leaving it up because I couldn't see other questions like it.

Upvotes: 0

Related Questions