Elliott James Elliott James - 26 days ago 8
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>
<select id="searchBy">
<option value="search-by=name&">name</option>
<option value="search-by=number&">number</option>
</select>


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
$("#filter").find("select").map(function(i){
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();
});


Summary

The above code returns

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


What am I doing wrong?

Answer

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
     return{
       text:  $(this).text(),
       value: this.value
     }
   }).get();
   // now an object for this select instance
   var obj={
     id:      this.id,
     options: opts // array from above   
   }
   return obj;   

}).get();

DEMO