在 Javascript 中对 JSON 对象进行排序

发布于 2024-10-03 06:43:08 字数 1955 浏览 5 评论 0原文

我一直在寻找

{"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 对象进行排序,但

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

我找不到任何可以执行此操作的代码。有人可以给我一些帮助吗?

I've been looking for a while to sort a JSON object like this

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

alphabetically by value of "COMMERCIALNAME_E" to get

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

I can't find any code that will do this. Can anyone give me some help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

泅人 2024-10-10 06:43:08
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);

更新:不要变异

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

UPDATED: DON'T MUTATE

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);
凉城 2024-10-10 06:43:08

首先提取 JSON 编码数据:

var data = JSON.parse(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;
});

我假设您想按 OBJECTID 排序,但您可以将其更改为按任何值排序。

First extract the JSON encoded data:

var data = JSON.parse(yourJSONString);
var results = data['results'];

Then sort with a custom(user) function:

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

I assumed you wanted to sort by OBJECTID, but you can change it to sort by anything.

丿*梦醉红颜 2024-10-10 06:43:08

您可以通过提供自定义比较函数作为 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;
    }
});

you can sort an ordered array of anything by providing a custom compare function as a parameter to 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;
    }
});
灯下孤影 2024-10-10 06:43:08

您可以使用 array.sort() 轻松完成此操作,

[
    { 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 }
// ]

示例取自此处< /a>,
此处了解更多信息

you can easily do it with array.sort()

[
    { 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 }
// ]

example is taken from here,
learn more about it from here

魔法唧唧 2024-10-10 06:43:08

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

You cannot sort a JSON string.. JSON is an Object Notation for data transport - ie, a string. You will have to evaluate it as an object literal (e.g. with eval) and make any changes you want before reserializing it.

檐上三寸雪 2024-10-10 06:43:08

从字符串排序中提取 JSON

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;

}

Extract the JSON from the String

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

Sort by passing a custom function to sort method

results.sort(customfunction);

custom function can be defined as

function customfunction(a, b) {

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

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文