0

I have an array that I use to generate a series of options that will be populated into a html select element. This currently works fine. I've done various benchmark testing and .map() is the most efficient approach.

My question is, how can I group the options within an optgroup element. I've tried using nested .map() but it out puts the options ungrouped still.

JS Fiddle https://jsfiddle.net/57gbxrzc/

const myOptsArr = [
        {
            title: 'Fruit',
            values: ['apple','pear','grapes','beer']
        },
        {
            title: 'Animals',
            values: ['apple','dog','mouse','cat']
        },
        // more here
    ];

let myOpts = `
    <option value="">Select Option</option>
  ${myOptsArr.map(item => `
        </optgroup label="${item.title}">${
        item.values.map(itemValue => `
                <option value="${itemValue}">${itemValue}</option>
            `).join('')}
        </optgroup>;
  `).join('')}
`;

document.getElementById('mySelect').innerHTML = myOpts;
4
  • Please describe the expected output.. Commented Jun 20, 2019 at 14:44
  • 1
    you are closing this tag </optgroup label="${item.title}">${ instead of opening it. It should be <optgroup label="${item.title}">${. Commented Jun 20, 2019 at 14:44
  • @PaulBota thanks! good catch. Please put it as an answer and i'll mark it as correct. Or should I just delete the question as it wasn't a logic issue? Commented Jun 20, 2019 at 14:48
  • Delete it most likely Commented Jun 20, 2019 at 14:49

2 Answers 2

1

You need to fix following problems

  • <optgroup> not </optgroup>
  • You don't need to join()

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

I can't see any difference b/w OP's link and your link. The code doesn't work in your fiddle. Also create a runnable snippet on SO instead of giving external links.
@MaheerAli oh just forgot to save, thanks for pointning out updated
0

You have a syntax error

</optgroup label="${item.title}">${
// change to
<optgroup ...

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.