Storing select options and optgroups in a JavaScript array

I'm making a jQuery plugin that loops through html select <option> tags and outputs them in a different format.
When looping through the options, I'd also like to maintain the relationship between them and <optgroup>s. Being a PHP guy I thought a multidimensional associative array would be the answer. So something like this:

<select>
    <optgroup label="group1">
        <option>option 1</option>
        <option>option 2</option>
    </optgroup>
    <optgroup label="group2">
        <option>option 3</option>
        <option>option 4</option>
    </optgroup>
</select>

...would turn into something like this:

myArray = [
    ['group1'] => ['option 1', 'option 2'],
    ['group2'] => ['option 3', 'option 4']
];

Is this possible in javascript or jQuery?

Answers:

Answer

Some fancy jQuery code, I believe it should work tested it, and it works as expected.

var o = {};

$('optgroup').each(function() {
    o[this.label] = $(this).find('option').map(function() {
        return $(this).text();
    }).get();
});

console.log(o);?

Live DEMO

Answer

It's possible, but as an object {} rather than an array [] (which in JavaScript has strictly ordered numeric keys, zero based):

myObj = {
  'group1': ['option 1', 'option 2'],
  'group2': ['option 3', 'option 4']
};

You might create it using something like the following in plain JavaScript.

var myObj = {};
// Get a reference to the <select>
var theSelect = document.getElementById('theSelect');
// And a node list of its <optgroup>
var optgroups = theSelect.getElementsByTagName('optgroup');
// Loop over the <optgroup>
for (var i=0; i<optgroups.length; i++) {
  // And create an object property named with the optgroup label
  myObj[optgroups[i].getAttribute('label')] = [];
  var options = optgroups[i].getElementsByTagName('option');
  // Loop over the <option>s inside it
  for (var j=0; j<options.length; j++) {
    // And stuff them into an array on the new object property:
    myObj[optgroups[i].getAttribute('label')].push(options[j].innerHTML);
  }
}
console.log(JSON.stringify(myObj));?
// {"group1":["option 1","option 2"],"group2":["option 3","option 4"]}

Here's a working fiddle.

Answer

You can store this as an object

myArray = {
    'group1' : ['option 1', 'option 2'],
    'group2' : ['option 3', 'option 4']
};

Here can access the options inside optgroup using ..

myArray.group1[0] // Will give you option 1 
myArray.group2[0] // Will give you option 3 

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.