javascriptmultiple-select

Pass multiple selected value and text as an array javascript


I have select field from where I can select multiple data. Now I want to access that value as key and value like array.

let selected_size = $(this).find(":selected").map(function(i, el) {
    var value = $(el).val();
    var text = $(el).text();
}).get();

I want to access the select value like this:

[1=>red,2=>green]

The numbers will be the actual value of color.

I tried to do:

let selected_size = $(this).find(":selected").map(function(i, el) {
     var value = $(el).val();
     var text = $(el).text();
     return [value=>text]
}).get();

But this does not seem to work.


Solution

  • In JavaScript, Objects are usually used to store Key / value pairs.
    Here's an example using JS's Array.prototype.reduce()

    $("select[multiple]").on("input", function() {
    
      const data = $(this).find(":selected").get().reduce((ob, el) => {
        ob[el.value] = el.textContent;
        return ob
      }, {});
      
      console.log(data);
    
    });
    <select multiple>
      <option value="1">Red</option>
      <option value="2">Blue</option>
      <option value="3">Green</option>
    </select>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>