Сортировка объекта JSON в Javascript
Я искал какое-то время для сортировки объекта 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", чтобы получить
{"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",
}
]}
Я не могу найти код, который сделает это. Может ли кто-нибудь помочь мне?
Ответы
Ответ 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);
ОБНОВЛЕНО: НЕ МУТАЕТ
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);
Ответ 2
Сначала извлеките 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;
});
Я предположил, что вы хотите сортировать по OBJECTID
, но вы можете изменить его, чтобы сортировать что угодно.
Ответ 3
вы можете отсортировать упорядоченный массив из всего, предоставив пользовательскую функцию сравнения в качестве параметра 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 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;
}
});
Ответ 4
Вы не можете сортировать строку JSON. JSON - это обозначение объекта для переноса данных, т.е. строка. Вы должны будете оценить его как литерал объекта (например, с помощью eval) и внести любые изменения, которые вы хотите, прежде чем повторно выполнять его.
Ответ 5
Извлеките 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;
}