3 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
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);
更新:請(qǐng)勿更改
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);

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
首先提取JSON編碼的數(shù)據(jù):
var data = eval(yourJSONString);
var results = data['results'];
然后使用自定義(用戶)函數(shù)進(jìn)行排序:
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;
});
我假設(shè)您想按排序OBJECTID,但是您可以將其更改為按任何排序。

TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以通過提供自定義比較功能作為的參數(shù),對(duì)任何東西的有序數(shù)組進(jìn)行排序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;
}
});
添加回答
舉報(bào)