在Javascript中对JSON对象排序

在Javascript中对JSON对象排序,javascript,json,sorting,object,Javascript,Json,Sorting,Object,我一直在寻找像这样对JSON对象进行排序的方法 {"results": [ { "layerId": 5, "layerName": "Pharmaceutical Entities", "attributes": { "OBJECTID": "35", "FACILITYTYPE": "Pharmacy", "FACILITYSUBTYPE": "24 Hr Pharmacy", "COMMERCIALNAME_E":

我一直在寻找像这样对JSON对象进行排序的方法

{"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",
   }
]}
按“COMMERCIALNAME_E”值的字母顺序获取


我找不到任何可以这样做的代码。有人能给我一些帮助吗?

您不能对JSON字符串排序。。JSON是数据传输的对象表示法,即字符串。您必须将其作为对象文本进行评估(例如,使用eval),并在重新序列化之前进行任何更改。

首先提取JSON编码的数据:

var data = eval(yourJSONString);
var results = data['results'];
然后使用自定义(用户)功能进行排序:

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;
});
results.sort(函数(a,b){
//返回a.attributes.OBJECTID-b.attributes.OBJECTID;
if(a.attributes.OBJECTID==b.attributes.OBJECTID)
返回0;
if(a.attributes.OBJECTIDb.attributes.OBJECTID)
返回1;
});

我假设您希望按
OBJECTID
排序,但您可以将其更改为按任何内容排序。

您可以通过提供自定义比较函数作为
array.sort()
的参数对任何内容的有序数组进行排序

var myObject=/*字符串中的json对象*/;
myObject.results.sort(函数(a,b){
//a和b将是列表中对象的两个实例
//可能的返回值
var a1st=-1;//负值表示左项应首先出现
var b1st=1;//正值表示应该首先出现正确的项
var equal=0;//零表示对象相等
//比较对象的属性值并确定其顺序
if(b.attributes.COMMERCIALNAME_E
函数sortjsonarrayproperty(对象、属性、方向){
if(arguments.length2?arguments[2]:1;//默认为升序
if(objArray&&objArray.constructor==数组){
变量propPath=(prop.constructor==数组)?prop:prop.split(“.”);
排序(函数(a,b){
for(propPath中的var p){
if(a[propPath[p]]和&b[propPath[p]]{
a=a[propPath[p]];
b=b[propPath[p]];
}
}
//将数字字符串转换为整数
a=a.match(/^\d+$/)?+a:a;
b=b.match(/^\d+$/)?+b:b;
返回((ab)?1*直接:0));
});
}
}
sortJsonArrayByProperty(结果,'attributes.OBJECTID');
SORTJSONArrayProperty(结果,'attributes.OBJECTID',-1);
更新:不要变异

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);
功能排序属性(对象、属性、方向){
if(arguments.length2?arguments[2]:1;//默认为升序
常量propPath=(prop.constructor==数组)?prop:prop.split(“.”);
clone.sort(函数(a,b){
for(让p进入propPath){
if(a[propPath[p]]和&b[propPath[p]]{
a=a[propPath[p]];
b=b[propPath[p]];
}
}
//将数字字符串转换为整数
a=a.match(/^\d+$/)?+a:a;
b=b.match(/^\d+$/)?+b:b;
返回((ab)?1*直接:0));
});
返回克隆;
}
const resultsByObjectId=sortByProperty(结果“attributes.OBJECTID”);
const resultsbyObjectedEssending=sortByProperty(结果“attributes.OBJECTID”,-1);

从字符串中提取JSON

var data = eval(given_JSON_string);
var results = data['results'];
通过将自定义函数传递给Sort方法进行排序

results.sort(customfunction);
自定义函数可以定义为

function customfunction(a, b) {

return a.attributes.COMMERCIALNAME_E < b.attributes.COMMERCIALNAME_E ? 1 : -1;
功能自定义功能(a、b){
返回a.attributes.COMMERCIALNAME_E

}

使用
array.sort()

示例取自

了解更多信息是的,没有“简单”排序json的解决方案。但有一个解决方案…你太棒了。感谢更新,对于可测试的代码,利用函数编程的强大功能,我不再在函数中变异args。值得注意的是,如果属性已经是整数,a.match将返回失败。你从不使用方向参数。当你可以
json.parse时,为什么
eval
?@customcommander很可能是因为这个答案是10年前的,
JSON.parse
当时没有完全的浏览器支持。请随意编辑您认为过时的答案。既然可以
JSON.parse
,为什么要
eval
var data = eval(given_JSON_string);
var results = data['results'];
results.sort(customfunction);
function customfunction(a, b) {

return a.attributes.COMMERCIALNAME_E < b.attributes.COMMERCIALNAME_E ? 1 : -1;
[
    { name: "Robin Van Persie", age: 28 },
    { name: "Theo Walcott", age: 22 },
    { name: "Bacary Sagna", age: 26  }
].sort(function(obj1, obj2) {
    // Ascending: first age less than the previous
    return obj1.age - obj2.age;
});
// Returns:  
// [
//    { name: "Theo Walcott", age: 22 },
//    { name: "Bacary Sagna", age: 26  },
//    { name: "Robin Van Persie", age: 28 }
// ]