Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

60
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda