Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

61
Visualizações
Create an object with selected value and optiongroup label

Let's suppose I have this dropdown with multiselection:

<select id='grp_option'>
  <optgroup label="Group 1">
    <option value='Option 1.1'>Option 1.1</option>
  </optgroup> 
  <optgroup label="Group 2">
    <option value='Option 2.1'>Option 2.1</option>
    <option value='Option 2.2'>Option 2.2</option>
  </optgroup>
</select>

I would like to create an array of object like this:

let array = [];
let obj, obj2;
obj[label] = value;
obj2[label2] = value2;
array.push(obj);
array.push(obj2);

Where label is the optgroup label of each selected option and value is the value of each selected option.

Do you have any idea? Thank you

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To do what you require you can use the map() method. Note that you can provide a variable in bracket notation as the name of the property.

Also note that I added the multiple attribute to the select to allow more than a single option to be selected - building an array of the values makes no sense without this.

let $select = $('#grp_option').on('change', () => {
  let arr = $select.find(':selected').map((i, el) => ({
    [$(el).closest('optgroup').prop('label')]: $(el).text()
  })).get();

  console.log(arr);
});
select {
  width: 150px;
  height: 175px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="grp_option" multiple>
  <optgroup label="Group 1">
    <option value="Option 1.1">Option 1.1</option>
  </optgroup>
  <optgroup label="Group 2">
    <option value="Option 2.1">Option 2.1</option>
    <option value="Option 2.2">Option 2.2</option>
  </optgroup>
  <optgroup label="Group 3">
    <option value="Option 3.1">Option 3.1</option>
    <option value="Option 3.2">Option 3.2</option>
    <option value="Option 3.2">Option 3.3</option>
  </optgroup>
</select>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda