2011-10-10 5 views
0

샘플 문자열이 JSON 개체를 정렬하는 방법을 확실하지 : 그 일에서jQuery를/자바 스크립트

var output = { 
     "myservices":[ 
     {"name":"oozie", "hostidn": "1", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}, 
     {"name":"oozie", "hostidn": "2", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}, 
     {"name":"oozie", "hostidn": "3", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}, 
     {"name":"oozie", "hostidn": "4", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}, 
     {"name":"oozie", "hostidn": "5", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}, 
     {"name":"single-namenode", "hostidn": "2", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"} 
]}; 

내 크래커 잭 시도합니다.

function sortJSONresultsByHost(a,b) 
{ 
    var objectIDA = parseInt(a.hostidn, 10) 
    var objectIDB = parseInt(b.hostidn, 10) 
    if(objectIDA === objectIDB) 
    { 
     return 0; 
    } 
    return objectIDA > objectIDB ? 1 : -1; 
} 
output.myservices.sort(sortJSONresultsByHost); 

실제로이 다양한 방법으로 정렬하는 방법을 알아야합니다. 예 : currstatusclass에 의해 hostidn에 의해. 그러나 나는 그것을 할 수있는 최선의 방법을 이해할 수 없다. 선택으로 할 수있는 함수를 만들 수있는 방법이 있습니까? 아니면 내가 원하는 방식으로 함수 집합을 만들 필요가 있습니까? 위의 광산이 나를 위해 밖으로 작동하지 않습니다.

답변

3
function sortObjectsByKey(objects, key){ 
    objects.sort(function() { 
     return function(a, b){ 
      var objectIDA = a[key]; 
      var objectIDB = b[key]; 
      if (objectIDA === objectIDB) { 
       return 0; 
      } 
      return objectIDA > objectIDB ? 1 : -1;   
     }; 
    }()); 
} 

sortObjectsByKey(output.myservices, "hostidn"); 
console.log(output.myservices); 
+0

동일한 개체 데이터가있는 다른 제목으로 가정하면 가장 높은 hostidn 값을 얻을 수있는 방법을 알 수 있습니까? – chris

+0

@chris 님이 사용자의 의견을 이해하지 못합니다 .. – wong2