我正在尝试订购一个我从JSON“转换”的对象。 我正在尝试使用我在this question上找到的这个功能,但它在我的情况下似乎不起作用:
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) );
});
}
}
这是我的JsFiddle
我想以3种不同的方式对其进行排序:
如果这个对象不是那么嵌套,我会知道怎么做。我可以调整这个功能吗?
答案 0 :(得分:1)
你还没有解释你想要的输出,所以这里是基于jsFiddle数据的逻辑猜测。
好的,这是来自你的jsFiddle的数据,这是一种可以理解的形式:
var obj = {saved: [
{"dict":"English","terms": [
{"term":"car","rowId":"3487","time":"1384773838069"},
{"term":"dog","rowId":"443","time":"1384776129957"},
{"term":"plane","rowId":"16171","time":"1384776168253"},
{"term":"bread","rowId":"127564","time":"1384959605196"}]
},
{"dict":"French","terms": [
{"term":"Monsieur","rowId":"934","time":"1384862250130"},
{"term":"Croissant","rowId":"13612","time":"1384900161187"},
{"term":"suis","rowId":"942","time":"1384900437068"}]
}
]
};
我假设你想要用它中的一个字段分别对每个术语数组进行排序。
以下是按字段排序的方法:
// utility function for sorting an array by a key in alpha order
function sortArrayAlpha(arr, key) {
arr.sort(function(a, b) {
return a[key].localeCompare(b[key]);
});
}
// utility function for sorting an array by a key in parsed numeric order
function sortArrayNum(arr, key) {
arr.sort(function(a, b) {
return parseInt(a[key], 10) - parseInt(b[key], 10);
});
}
// sort by term
var dicts = obj.saved;
// cycle through each item in the saved array
for (var i = 0; i < dicts.length; i++) {
var terms = dicts[i].terms;
sortArrayAlpha(terms, "term");
}
// sort by time
// cycle through each item in the saved array
for (var i = 0; i < dicts.length; i++) {
var terms = dicts[i].terms;
sortArrayNum(terms, "time");
}
// sort by rowId
// cycle through each item in the saved array
for (var i = 0; i < dicts.length; i++) {
var terms = dicts[i].terms;
sortArrayNum(terms, "rowId");
}
并且,显示输出的jsFiddle:http://jsfiddle.net/jfriend00/vH8u7/。您可以在jsFiddle中看到每种排序的确切输出格式。
以下是按术语排序的内容:
{"saved":[
{"dict":"English","terms":[
{"term":"bread","rowId":"127564","time":"1384959605196"},
{"term":"car","rowId":"3487","time":"1384773838069"},
{"term":"dog","rowId":"443","time":"1384776129957"},
{"term":"plane","rowId":"16171","time":"1384776168253"}]},
{"dict":"French","terms":[
{"term":"Croissant","rowId":"13612","time":"1384900161187"},
{"term":"Monsieur","rowId":"934","time":"1384862250130"},
{"term":"suis","rowId":"942","time":"1384900437068"}]
}
]}