在 Javascript 中对 JSON 对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4222690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a JSON object in Javascript
提问by Venkatesh Goud
I've been looking for a while to sort a JSON object like this
我一直在寻找对这样的 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",
}
]}
alphabetically by value of "COMMERCIALNAME_E" to get
按字母顺序按“COMMERCIALNAME_E”的值得到
{"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?
我找不到任何可以执行此操作的代码。任何人都可以给我一些帮助吗?
回答by PDA
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);
回答by Alin Purcaru
First extract the JSON encoded data:
首先提取JSON编码数据:
var data = eval(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.
我假设您想按 排序OBJECTID
,但您可以将其更改为按任何排序。
回答by lincolnk
you can sort an ordered array of anything by providing a custom compare function as a parameter to Array.Sort()
.
您可以通过提供自定义比较函数作为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;
}
});
回答by Hamish
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.
您不能对 JSON 字符串进行排序。JSON 是用于数据传输的对象表示法 - 即字符串。您必须将其作为对象文字(例如使用 eval)进行评估,并在重新序列化之前进行任何您想要的更改。
回答by Irteza Asad
you can easily do it with array.sort()
你可以很容易地做到这一点 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 }
// ]
回答by abhishek kumar
Extract the JSON from the String
从字符串中提取 JSON
var data = eval(given_JSON_string);
var results = data['results'];
Sort by passing a custom function to sort method
通过将自定义函数传递给 sort 方法进行排序
results.sort(customfunction);
custom function can be defined as
自定义函数可以定义为
function customfunction(a, b) {
return a.attributes.COMMERCIALNAME_E < b.attributes.COMMERCIALNAME_E ? 1 : -1;
}
}