问题描述
首先,我有一个JSON对象,例如:
{
allSitesInfo:[{
title:Site001,
网站:http://www.example.com/,
lat:22.70896,
lng :120.35197,
内容:{
PR:87.89,
kWh:1700
},
类型:grn-blank
}
]
}
这是我的所有网站列表。包含四种类型的电站的能源状况。
但是,我需要根据优先顺序重新排序。
优先级从高到低:
设备已断开(type:X
)
系统错误(type:暂停
)
部分系统错误 (type:wht-stars
)
将未知类型排序到最后。
var order = {X:1,pause:2,wht-stars:3,grn-blank:4,默认值:Infinity };
array.sort(函数(a,b){
return(order [a.type] || order.default) - (order [b.type] || order.default );
});
First off, I have a JSON object such as:
{
"allSitesInfo": [{
"title": "Site001",
"website": "http://www.example.com/",
"lat": "22.70896",
"lng": "120.35197",
"content": {
"PR": "87.89",
"kWh": "1700"
},
"type": "grn-blank"
}
]
}
Here's my all sites list. The energy situation of the power station which contains four types.However, I need to re-order the list according to priorities.
Priorities from high to low:
Device Disconnected ("type": "X"
)
System Error ("type": "pause"
)
Partial System Error ("type": "wht-stars"
)
System Normal ("type": "grn-blank"
)
Here are my code snippets:
function GetRealTimeList() {
var url = "ajaxHandler.jhp";
var args = {};
args["task"] = "GetRealTimeList";
$.ajax({
"url": url,
method: "GET",
data: args,
})
.done(function (data) {
var allSites = JSON.parse(data);
for (var i = 0; i < allSites["allSitesInfo"].length; i++) {
$("#custom-search-site").append("<li><img src=\"img/paddle/"+ allSites["allSitesInfo"][i]["type"] +"_maps.png\" class=\"blank\"><span>"+ allSites["allSitesInfo"][i]["title"] +"</span></li>");
}
})
.fail(function (data) {
console.log("Get real time data fail. " + data);
});
}
How can I do this in javascript SE5?
You could take an object as hash table for the wanted order and use that object for sorting.
default
contains a huge value Infinity
to sort unknown types to the end.
var order = { "X": 1, "pause": 2, "wht-stars": 3, "grn-blank": 4, default: Infinity };
array.sort(function (a, b) {
return (order[a.type] || order.default) - (order[b.type] || order.default);
});
这篇关于按优先级排序JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!