Home > Net >  Create an object with selected value and optiongroup label
Create an object with selected value and optiongroup label

Time:01-25

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

CodePudding user response:

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>

  •  Tags:  
  • Related