我有这个简单的JSON表,其中元素需要按照alpabetical顺序按值排序,另一个按名称按顺序排序。有人可以给我一个例子我会怎么做才能理解它?
{
"sortingTask": [
{"sortAlpabeticallyByValue": [
{"string":"äää"},
{"string":"bee"},
{"string":"aaa"},
{"string":"öoöo"},
{"string":"OöOö"},
]},
{"sortAlpabeticallyByName": [
{"stringB":"testi1"},
{"stringÄ":"testi2"},
{"stringA":"testi3"}
]},
{"sortAlpabetically": [
"äää","bee","baa"
]}
]
}
答案 0 :(得分:0)
You need to implement custom sort method using switch case. For comparison between two words you can use localeCompare
var data = { "sortingTask": [ {"sortAlpabeticallyByValue": [ {"string":"äää"}, {"string":"bee"}, {"string":"aaa"}, {"string":"öoöo"}, {"string":"OöOö"}, ]}, {"sortAlpabeticallyByName": [{"stringB":"testi1"}, {"stringÄ":"testi2"}, {"stringA":"testi3"} ]}, {"sortAlpabetically":[ "äää","bee","baa" ]}]};
data.sortingTask.forEach(function(obj){
Object.keys(obj).forEach(function(k){
switch(k){
case 'sortAlpabeticallyByValue' :
obj[k].sort(function(a,b){
return a.string.localeCompare(b.string, undefined, { sensitivity: 'variant' });
});
break;
case 'sortAlpabetically':
obj[k].sort(function(a,b){
return a.localeCompare(b, undefined, {sensitivity: 'variant'});
});
break;
case 'sortAlpabeticallyByName':
obj[k].sort(function(a,b){
return Object.keys(a)[0].localeCompare(Object.keys(b)[0]);
});
break;
}
});
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }