我有一个对象,我正在使用ng-repeat
,但需要以可排序的格式显示项目
如果对于多个项目的总值相同,则应该对总值进行排序,如果p1与p2相同,则基于p1值进行排序,如果p2也相同,那么p3.i已经基于总数排序了对象值,但优先考虑如何基于多个对象属性进行排序?
我已经根据价值和关键进行了排序,但在这种复杂的情况下需要帮助
{ "QVC":{
"p1":0,
"p2":12,
"p3":12,
"total":24,
"org":"QVC"
},
"TURNER & TOWNSEND":{
"p1":12,
"p2":12,
"p3":0,
"total":24,
"org":"TURNER & TOWNSEND"
},
"EDF ENERGY":{
"p1":12,
"p2":0,
"p3":12,
"total":24,
"org":"EDF ENERGY"
},
"TOWERS WATSON":{
"p1":6,
"p2":0,
"p3":6,
"total":12,
"org":"TOWERS WATSON"
},
"VODAFONE UK LTD":{
"p1":0,
"p2":1,
"p3":0,
"total":1,
"org":"VODAFONE UK LTD"
},
"DENPLAN LTD":{
"p1":1,
"p2":0,
"p3":0,
"total":1,
"org":"DENPLAN LTD"
}
}
答案 0 :(得分:2)
您可以先创建一个数组,然后使用Array#sort()
和带有所需排序层次结构的回调对其进行排序。
var object = { "QVC": { "p1": 0, "p2": 12, "p3": 12, "total": 24, "org": "QVC" }, "TURNER & TOWNSEND": { "p1": 12, "p2": 12, "p3": 0, "total": 24, "org": "TURNER & TOWNSEND" }, "EDF ENERGY": { "p1": 12, "p2": 0, "p3": 12, "total": 24, "org": "EDF ENERGY" }, "TOWERS WATSON": { "p1": 6, "p2": 0, "p3": 6, "total": 12, "org": "TOWERS WATSON" }, "VODAFONE UK LTD": { "p1": 0, "p2": 1, "p3": 0, "total": 1, "org": "VODAFONE UK LTD" }, "DENPLAN LTD": { "p1": 1, "p2": 0, "p3": 0, "total": 1, "org": "DENPLAN LTD" } },
array = Object.keys(object).map(function (k) { return object[k]; });
array.sort(function (a, b) {
return a.total - b.total || a.p1 - b.p1 || a.p2 - b.p2 || a.p3 - b.p3;
});
console.log(array);
答案 1 :(得分:1)
您无法对对象进行排序,但可以使用Object.keys()
创建对象键数组并对其进行排序
var obj = {"QVC":{"p1":0,"p2":12,"p3":12,"total":24,"org":"QVC"},"TURNER & TOWNSEND":{"p1":12,"p2":12,"p3":0,"total":24,"org":"TURNER & TOWNSEND"},"EDF ENERGY":{"p1":12,"p2":0,"p3":12,"total":24,"org":"EDF ENERGY"},"TOWERS WATSON":{"p1":6,"p2":0,"p3":6,"total":12,"org":"TOWERS WATSON"},"VODAFONE UK LTD":{"p1":0,"p2":1,"p3":0,"total":1,"org":"VODAFONE UK LTD"},"DENPLAN LTD":{"p1":1,"p2":0,"p3":0,"total":1,"org":"DENPLAN LTD"}}
var sort = Object.keys(obj).sort(function(a, b) {
return obj[b].total - obj[a].total || obj[b].p1 - obj[a].p1 || obj[b].p2 - obj[a].p2 || obj[b].p3 - obj[a].p3;
})
console.log(sort)
然后,您可以使用该排序的键数组按排序顺序返回对象值
var obj = {"QVC":{"p1":0,"p2":12,"p3":12,"total":24,"org":"QVC"},"TURNER & TOWNSEND":{"p1":12,"p2":12,"p3":0,"total":24,"org":"TURNER & TOWNSEND"},"EDF ENERGY":{"p1":12,"p2":0,"p3":12,"total":24,"org":"EDF ENERGY"},"TOWERS WATSON":{"p1":6,"p2":0,"p3":6,"total":12,"org":"TOWERS WATSON"},"VODAFONE UK LTD":{"p1":0,"p2":1,"p3":0,"total":1,"org":"VODAFONE UK LTD"},"DENPLAN LTD":{"p1":1,"p2":0,"p3":0,"total":1,"org":"DENPLAN LTD"}}
var sort = Object.keys(obj).sort(function(a, b) {
return obj[b].total - obj[a].total || obj[b].p1 - obj[a].p1 || obj[b].p2 - obj[a].p2 || obj[b].p3 - obj[a].p3;
})
sort.forEach(function(e) {console.log(obj[e]) });