2013-03-28 53 views
0

我有一個JSON對象:mootools的JSON選擇列表

var data = {"options" :[  
     {"name": "Size", "value": "S", "price": "10", "order": "1"}, 
     {"name": "Size", "value": "M", "price": "12", "order": "2"}, 
     {"name": "Size", "value": "XL", "price": "14", "order":"3"}, 
     {"name": "Color", "value": "Red", "price": "14", "order":"2"},  
     {"name": "Color", "value": "Green", "price": "12", "order": "1"} 
    ]} 

我如何轉換這種使用mootools的javascript庫選擇列表?

<div> 
<label>Size:</label> 
<select name="options[size]"> 
    <option value="10">S</option> 
    <option value="12">M</option> 
    <option value="14">XL</option> 
</select> 
<label>Color:</label> 
<select name="options[color]"> 
    <option value="12">Green</option> 
    <option value="14">Red</option> 
</select> 
</div> 

謝謝!

回答

1

它只是用數據玩一點點 - 你去那裏: http://jsfiddle.net/XRH6r/

var data = {"options" :[  
     {"name": "Size", "value": "S", "price": "10", "order": "1"}, 
     {"name": "Size", "value": "M", "price": "12", "order": "2"}, 
     {"name": "Size", "value": "XL", "price": "14", "order":"3"}, 
     {"name": "Color", "value": "Red", "price": "14", "order":"2"},  
     {"name": "Color", "value": "Green", "price": "12", "order": "1"} 
    ]}; 

//create unique map according to the data: 
var arr = data.options; 
var map = {}; 
arr.each(function(item){ 
    var name = item.name; 
    var o; 
    if(map[name]){ 
     o = map[name];  
    } 
    else{ 
     o = {}; 
     o.options = []; 
     map[name] = o; 
    } 
    o.options.push({value:item.value,price:item.price,order:Number(item.order)}); 
}); 

//sort options array to be ordered by order 
//and then build the select 
Object.each(map,function(item,name){ 
    item.options.sort(function(a,b){ 
      return a.order > b.order; 
    }); 
    var label = new Element('label').set('html',name); 
    var combo = new Element('select'); 
    item.options.each(function(opt){ 
     combo.options[combo.options.length] = new Option(opt.value,opt.price);  
    }); 

    label.inject(document.body); 
    combo.inject(document.body); 
});