搜索但没有得到正确的解决方案。
我有一个来自服务器的json字符串。我想将字符串转换为javascript数组,以便我可以根据“hotel_name”,“minPrice”,“hotel_star”对数据进行排序。
这是JSON字符串。
{
"00001065": {
"hotel_id": "00001065",
"hotel_name": "The Infantry Hotel",
"hotel_star": "3",
"image": "",
"location": "Infantry Road",
"minPrice": "2,497",
"RoomTypes": [
{
"RoomTypeName": "Deluxe King / Twin Double",
"AvailableQuantity": "4",
"RatePlanInclusions": "Complimentary Wi-Fi Internet",
"price": "2,497"
},
{
"RoomTypeName": "Superior Double",
"AvailableQuantity": "2",
"RatePlanInclusions": "Breakfast",
"price": "3,496"
}
]
},
"00001080": {
"hotel_id": "00001080",
"hotel_name": "Hotel Ramanashree",
"hotel_star": "3",
"image": "",
"location": "Richmond Road",
"minPrice": "3,879",
"RoomTypes": [
{
"RoomTypeName": "Executive Room",
"AvailableQuantity": "25",
"RatePlanInclusions": "Breakfast",
"price": "3,879"
},
{
"RoomTypeName": "Club Room",
"AvailableQuantity": "25",
"RatePlanInclusions": "Breakfast",
"price": "4,604"
}
]
},
"00003757": {
"hotel_id": "00003757",
"hotel_name": "The Paul ",
"hotel_star": "5",
"image": "",
"location": "Domlur Layout",
"minPrice": "6,216",
"RoomTypes": [
{
"RoomTypeName": "Executive Suite - Two Bedrooms Suite",
"AvailableQuantity": "4",
"RatePlanInclusions": "Complimentary Wi-Fi Internet, Breakfast",
"price": "8,942"
},
{
"RoomTypeName": "Premier Suite - Two Bedrooms Suite",
"AvailableQuantity": "2",
"RatePlanInclusions": "Complimentary Wi-Fi Internet, Breakfast",
"price": "10,718"
},
{
"RoomTypeName": "Studio Suite - One Bedroom Suite",
"AvailableQuantity": "4",
"RatePlanInclusions": "Complimentary Wi-Fi Internet, Breakfast",
"price": "6,216"
}
]
}
}
答案 0 :(得分:1)
这是非常标准的JavaScript。也许你应该先尝试一下JSON教程? MDN是一个很好的起点。
您可以解析JSON并将其转换为数组。
// Converts an object into an array
function objectToArray(obj) {
var array = [];
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
array.push(obj[prop]);
}
}
return array;
}
var obj = JSON.parse(json_string);
var arr = objectToArray(obj);
现在,您可以使用自己的compareFunction对sort()数组进行排序。
答案 1 :(得分:0)
您不需要将json对象转换为数组以进行排序。 您可以对JSON本身进行排序。
function sortResults(prop, asc) {
arr = arr.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]);
else return (b[prop] > a[prop]);
});
}
我已经用你的Json创建了一个工作示例。单击标题以查看此示例中的排序:http://jsfiddle.net/VAKrE/922/
答案 2 :(得分:0)
你可以这样做:
var o = JSON.parse("...");
var asArray = Object.keys(o).map(function(k) { return o[k] });
asArray.sort(function(a, b) {
if(a.hotel_name > b.hotel_name) return 1;
if(a.hotel_name < b.hotel_name) return -1;
return 0;
});
答案 3 :(得分:-1)
var myObject = JSON.parse(jsonString);