JS對象沒有順序。您無法以編程方式對對象進行排序。只有陣列
不是真的。當您在對象上調用JSON.stringify
時,輸出字符串中屬性的順序是在該對象上定義屬性的順序。這同樣適用於Object.keys(obj)
和for(var property in obj)
(假設obj
是您的對象)。你可以這樣做:
var originalObject = {
"accommodation" : "Accommodation",
"bed-breakfast" : "Bed & Breakfast",
"caravan-camping" : "Caravan & Camping",
"cottages" : "Cottages",
"friends-family" : "Friends & Family",
"health-spas" : "Health Spas",
"hostels" : "Hostels",
"hotels" : "Hotels",
"self-catering" : "Self Catering",
"backpacking" : "Backpacking",
"car-touring" : "Car Touring"
};
// map your object onto an array [key, value]
var arr = _.map(originalObject, function(value, key) {
return [key, value];
});
// sort it by originalObject's values
arr.sort(function(a, b) {
return a[1].localeCompare(b[1]);
});
// create an object from an array
var obj = _.object(arr);
JSON.stringify(originalObject)
產量:
"{"accommodation":"Accommodation","bed-breakfast":"Bed & Breakfast","caravan-camping":"Caravan & Camping","cottages":"Cottages","friends-family":"Friends & Family","health-spas":"Health Spas","hostels":"Hostels","hotels":"Hotels","self-catering":"Self Catering","backpacking":"Backpacking","car-touring":"Car Touring"}"
JSON.stringify(obj)
產量:
"{"accommodation":"Accommodation","backpacking":"Backpacking","bed-breakfast":"Bed & Breakfast","car-touring":"Car Touring","caravan-camping":"Caravan & Camping","cottages":"Cottages","friends-family":"Friends & Family","health-spas":"Health Spas","hostels":"Hostels","hotels":"Hotels","self-catering":"Self Catering"}"
JS對象沒有順序。您無法以編程方式對對象進行排序。只有數組。 – Andy
我只是想說,安迪:D –
我強烈建議**不要**存儲HTML轉義的文本。在HTML上下文中使用它時,應將其轉換爲HTML。否則,你很早就混淆了你的數據方式,並且不能將它用於其他目的。 – Brad