有關於jquery each 照順序排序

edited 十月 2013 in Javascript
各位好,小弟又來請教問題了 ^^"

小弟有一組json資料
[{"id":"3","itemid":"3","val":"b1","parent":"1","type":"pay"},{"id":"7","itemid":"8","val":"b2","parent":"1","type":"pay"}]

我是用each去把它依序print出來

但是一直無法依照itemid的大小排列

想問各位大大如何讓each依照itemid排列呢?

附上程式碼
function tree_list(id){

  $.getJSON("do.php?action=get&i="+id,function(list_json){

    $.each(list_json,function(i,item){
   
       //依序列出json值
       return tree_list(item.itemid);//遞迴

    });
  
  });

}


原始討論: http://twpug.net/x/modules/newbb/viewtopic.php?topic_id=6819

評論

  • edited 八月 2012
    <script>
    var json_list=[{"id":"3","itemid":"3","val":"b1","parent":"1","type":"pay"},{"id":"7","itemid":"8","val":"b2","parent":"1","type":"pay"}];
    var item=new Array();
    $.each(json_list,function(k,v)
    {
    	item.push(v.itemid);
    });
    item.sort();
    $.each(item,function(k,v)
    {
    	alert(v);
    });
    </script>
    
  • edited 八月 2012
    <script> 
    var json_list=[
    	{"id":"3","itemid":"10","val":"b1","parent":"1","type":"pay"},
    	{"id":"7","itemid":"8","val":"b2","parent":"1","type":"pay"},
    	{"id":"10","itemid":"9","val":"b2","parent":"1","type":"pay"}
    ]; 
    
    json_list.sort(function(a,b) {
    	var compA = parseInt(a.itemid,10);
    	var compB = parseInt(b.itemid,10);
    	return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    });
    console.log(json_list);
    </script>
    

    javascript 就有原生 sort , 這個範例存到 html , 直接用 chrome 執行 , 要打開開發人員工具中的Console , 就會看到以排序好的物件
  • edited 八月 2012
    有了,感謝兩位大大的幫忙 :)
Sign In or Register to comment.