2010-11-19 9 views
16

J'ai cherché pendant un certain temps pour trier un objet JSON comme celui-ciTri un objet JSON en 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", 
    } 
]} 

par ordre alphabétique pour obtenir

{"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", 
    } 
]} 

Je ne peux en valeur de « COMMERCIALNAME_E » t trouver tout code qui fera cela. Est-ce que quelqu'un peut m'aider?

+0

sorte que ... comment? – Alex

+1

ctrl + K est votre ami. Utilisez-le lors de la publication du code. –

Répondre

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); 

MISE À JOUR: NE PAS mutent

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

Oui, il n'y a pas de solution "facile" pour trier json. Mais ther est une solution ... Vous êtes tellement goood. –

+0

merci mise à jour, pour le code testable, puissance de harnais de la programmation fonctionnelle je ne mute plus args dans mes fonctions. – PDA

1

Vous ne pouvez pas trier une chaîne JSON. JSON est une notation d'objet pour le transport de données, c'est-à-dire une chaîne. Vous devrez l'évaluer en tant que littéral d'objet (par exemple avec eval) et apporter les modifications souhaitées avant de le reséraliser.

8

premier extrait les données codées JSON:

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

Ensuite sorte avec une fonction personnalisée (utilisateur):

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; 
}); 

Je suppose que vous vouliez trier par OBJECTID, mais vous pouvez changer trier par n'importe quoi.

+0

Il devrait être en minuscules ** b. ** dans les déclarations +1 –

3

Vous pouvez trier un tableau ordonné de n'importe quoi en fournissant une fonction de comparaison personnalisée en tant que paramètre à 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

Extrait du JSON de la chaîne

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

Trier par le passage d'une fonction personnalisée pour trier méthode

results.sort(customfunction); 
fonction

personnalisée peut être définie comme

function customfunction(a, b) { 

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

}