Elliott James Elliott James - 1 year ago 80
jQuery Question

Convert HTML selector into Object

I am creating a script that turns HTML selectors into customisable menus. I need to return a nested Object(like Fig 2) from my HTML.

i.e return this
Fig 1

<select id="orderBy">
<option value="order-by=newest&">newest</option>
<option value="order-by=relevance&">relevance</option>
<select id="searchBy">
<option value="search-by=name&">name</option>
<option value="search-by=number&">number</option>

as an Object like so:
Fig 2

selectors = [
{"id":"orderBy", "options" : [
{"value":"search-by=newest&", "name":"search-by=relevance&"}
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"search-by=number&"}

My code so far, although this doesn't work.

var selector = new Object;

//Find all select boxes and push their ID's' into selector
selector[i] = this.id;

//Find all select boxes and push their ID's' into selector
$("#" + selector[i]).find("option").map(function(i){
optionText[i] = $(this).text();
optionValue[i] = $(this).val();


The above code returns

Object {0: "orderBy", 1: "searchBy"}.

What am I doing wrong?

Answer Source

In order to create an array using map() you need to return an object within the callback.

You probably want something more like

var data = $('#container select').map(function(){
   // create array of option objects for this select instance
   var opts = $(this).children().map(function(){
      // return an object for each element of array
       text:  $(this).text(),
       value: this.value
   // now an object for this select instance
   var obj={
     id:      this.id,
     options: opts // array from above   
   return obj;   



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download