gpt4 book ai didi

javascript - 根据优先级对基于多个属性的javascript对象进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:39 27 4
gpt4 key购买 nike

我有一个对象,我正在使用 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"
}

}

最佳答案

可以先做一个数组,然后用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);

关于javascript - 根据优先级对基于多个属性的javascript对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37566360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com