简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM