2010-11-19 9 views
16

Ho cercato per un po 'di ordinare un oggetto JSON come questoordinamento di un oggetto JSON in Javascript

{"results": [ 
    { 
    "layerId": 5, 
    "layerName": "Pharmaceutical Entities", 
    "attributes": { 
     "OBJECTID": "35", 
     "FACILITYTYPE": "Pharmacy", 
     "FACILITYSUBTYPE": "24 Hr Pharmacy", 
     "COMMERCIALNAME_E": "SADD MAARAB PHARMACY", 
     }, 
    "geometryType": "esriGeometryPoint", 
    }, 
    { 
    "layerId": 5, 
    "layerName": "Pharmaceutical Entities", 
    "attributes": { 
     "OBJECTID": "1", 
     "FACILITYTYPE": "Pharmacy", 
     "FACILITYSUBTYPE": "24 Hr Pharmacy", 
     "COMMERCIALNAME_E": "GAYATHY HOSPITAL PHARMACY", 

    }, 
    "geometryType": "esriGeometryPoint", 
    }, 
    { 
    "layerId": 5, 
    "layerName": "Pharmaceutical Entities", 
    "attributes": { 
     "OBJECTID": "255", 
     "FACILITYTYPE": "Pharmacy", 
     "FACILITYSUBTYPE": "24 Hr Pharmacy", 
     "COMMERCIALNAME_E": "AL DEWAN PHARMACY", 
     }, 
    "geometryType": "esriGeometryPoint", 
    } 
]} 

in ordine alfabetico in base al valore di "COMMERCIALNAME_E" per ottenere

{"results": [ 
    { 
    "layerId": 5, 
    "layerName": "Pharmaceutical Entities", 
    "attributes": { 
     "OBJECTID": "255", 
     "FACILITYTYPE": "Pharmacy", 
     "FACILITYSUBTYPE": "24 Hr Pharmacy", 
     "COMMERCIALNAME_E": "AL DEWAN PHARMACY", 
     }, 
    "geometryType": "esriGeometryPoint", 
    }, 
    { 
    "layerId": 5, 
    "layerName": "Pharmaceutical Entities", 
    "attributes": { 
     "OBJECTID": "1", 
     "FACILITYTYPE": "Pharmacy", 
     "FACILITYSUBTYPE": "24 Hr Pharmacy", 
     "COMMERCIALNAME_E": "GAYATHY HOSPITAL PHARMACY", 
     }, 
    "geometryType": "esriGeometryPoint", 
    }, 
    { 
    "layerId": 5, 
    "layerName": "Pharmaceutical Entities", 
    "attributes": { 
     "OBJECTID": "35", 
     "FACILITYTYPE": "Pharmacy", 
     "FACILITYSUBTYPE": "24 Hr Pharmacy", 
     "COMMERCIALNAME_E": "SADD MAARAB PHARMACY", 
     }, 
    "geometryType": "esriGeometryPoint", 
    } 
]} 

posso' trovare un codice che faccia questo. Qualcuno può darmi un aiuto?

+0

sorta cosa ... come? – Alex

+1

ctrl + K è tuo amico. Usalo quando pubblichi il codice. –

risposta

35
function sortJsonArrayByProperty(objArray, prop, direction){ 
    if (arguments.length<2) throw new Error("sortJsonArrayByProp requires 2 arguments"); 
    var direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending 

    if (objArray && objArray.constructor===Array){ 
     var propPath = (prop.constructor===Array) ? prop : prop.split("."); 
     objArray.sort(function(a,b){ 
      for (var p in propPath){ 
       if (a[propPath[p]] && b[propPath[p]]){ 
        a = a[propPath[p]]; 
        b = b[propPath[p]]; 
       } 
      } 
      // convert numeric strings to integers 
      a = a.match(/^\d+$/) ? +a : a; 
      b = b.match(/^\d+$/) ? +b : b; 
      return ((a < b) ? -1*direct : ((a > b) ? 1*direct : 0)); 
     }); 
    } 
} 

sortJsonArrayByProperty(results, 'attributes.OBJECTID'); 
sortJsonArrayByProperty(results, 'attributes.OBJECTID', -1); 

AGGIORNAMENTO: NON mutare

function sortByProperty(objArray, prop, direction){ 
    if (arguments.length<2) throw new Error("ARRAY, AND OBJECT PROPERTY MINIMUM ARGUMENTS, OPTIONAL DIRECTION"); 
    if (!Array.isArray(objArray)) throw new Error("FIRST ARGUMENT NOT AN ARRAY"); 
    const clone = objArray.slice(0); 
    const direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending 
    const propPath = (prop.constructor===Array) ? prop : prop.split("."); 
    clone.sort(function(a,b){ 
     for (let p in propPath){ 
       if (a[propPath[p]] && b[propPath[p]]){ 
        a = a[propPath[p]]; 
        b = b[propPath[p]]; 
       } 
     } 
     // convert numeric strings to integers 
     a = a.match(/^\d+$/) ? +a : a; 
     b = b.match(/^\d+$/) ? +b : b; 
     return ((a < b) ? -1*direct : ((a > b) ? 1*direct : 0)); 
    }); 
    return clone; 
} 

const resultsByObjectId = sortByProperty(results, 'attributes.OBJECTID'); 
const resultsByObjectIdDescending = sortByProperty(results, 'attributes.OBJECTID', -1); 
+0

Sì, non esiste una soluzione "facile" per l'ordinamento di JSON. Ma c'è una soluzione ... Sei così buono. –

+0

grazie aggiornato, per il codice testabile, potenza di cablaggio della programmazione funzionale Non muto più gli argomenti nelle mie funzioni. – PDA

1

Non è possibile ordinare una stringa JSON. JSON è una notazione oggetto per il trasporto dati, ad esempio una stringa. Dovrai valutarlo come un oggetto letterale (ad es. Con eval) e apportare le modifiche che desideri prima di riscriverlo.

8

Prima estrarre i dati JSON codificato:

var data = eval(yourJSONString); 
var results = data['results']; 

Poi sorta con una funzione personalizzata (utente):

results.sort(function(a,b){ 
    //return a.attributes.OBJECTID - b.attributes.OBJECTID; 
    if(a.attributes.OBJECTID == b.attributes.OBJECTID) 
     return 0; 
    if(a.attributes.OBJECTID < b.attributes.OBJECTID) 
     return -1; 
    if(a.attributes.OBJECTID > b.attributes.OBJECTID) 
     return 1; 
}); 

ho pensato che si voleva ordinare in base OBJECTID, ma si può cambiare per ordinare da qualsiasi cosa.

+0

Dovrebbe essere minuscolo ** b. ** in istruzioni +1 –

3

è possibile ordinare un array ordinato di qualsiasi cosa fornendo una funzione di confronto personalizzata come parametro a Array.Sort().

var myObject = /* json object from string */ ; 

myObject.results.sort(function (a, b) { 

    // a and b will be two instances of your object from your list 

    // possible return values 
    var a1st = -1; // negative value means left item should appear first 
    var b1st = 1; // positive value means right item should appear first 
    var equal = 0; // zero means objects are equal 

    // compare your object's property values and determine their order 
    if (b.attributes.COMMERCIALNAME_E < a.attributes.COMMERCIALNAME_E) { 
     return b1st; 
    } 
    else if (a.attributes.COMMERCIALNAME_E < b.attributes.COMMERCIALNAME_E) { 
     return a1st; 
    } 
    else { 
     return equal; 
    } 
}); 
0

Estrarre il JSON dalla stringa

var data = eval(given_JSON_string); 
var results = data['results']; 

Ordina passando una funzione personalizzata per ordinare metodo

results.sort(customfunction); 

funzione personalizzata può essere definita come

function customfunction(a, b) { 

return a.attributes.COMMERCIALNAME_E < b.attributes.COMMERCIALNAME_E ? 1 : -1; 

}

Problemi correlati