简体   繁体   English

带条件的键对象排序

[英]sort Object of keys with conditions

I have the below Object我有以下对象

Object={
   '11': 1.2317655481421725,
   '12': 1.233489927305401,
   '13': 1.2317655481421725,
   '14': 1.233489927305401,
   '15': 1.205620575126925,
   '16': 1.2600762465738233,
   '17': 1.205620575126925,
   '18': 1.2600762465738233,
   '41': 0.8577882967879851,
   '42': 0.8890249774881712,
   '43': 0.8577882967879851,
   '44': 0.8890249774881712,
   '45': 0.8268651773658509,
   '46': 0.8977620865671874,
   '47': 0.8268651773658509,
   '48': 0.8977620865671874
 }

which I need to order by the values according to some conditions我需要根据某些条件按值排序

  • when the values of the keys are equal, check a flag of each one of the keys that may be either 0 or 1, and sort first the one with flag=1当键的值相等时,检查每个键的标志(可能是 0 或 1),并首先对标志 = 1 的那个进行排序
  • in any other case sort all the rest keys by value in descending order在任何其他情况下,按值按降序对所有其余键进行排序

The code I run looks like below我运行的代码如下所示

keysSorted = Object.keys(Object).sort(function(a,b){

Flag_b=parseInt(Products[Object.keys(Object)[b-1]]['attribute'])
Flag_a=parseInt(Products[Object.keys(Object)[a-1]]['attribute'])
// console.log('key a',Object.keys(Object)[a-1],'Flag_a ', Flag_a, 'key b',Object.keys(Object)[b-1],'Flag_b', Flag_b)

//case equal utilities
if ((Object[b]===Object[a]) && (user.answer===1)){
    key_a=Object.keys(Object)[a-1]
    key_b=Object.keys(Object)[b-1]
    console.log('true equality','key_b',key_b,'Object[b]',Object[b],'key a',key_a,'Object[a]',Object[a])
    console.log('key a',key_a,'Flag_a ', Flag_a, 'key b',key_b,'Flag_b', Flag_b)
    if (Flag_a===1){
        return -1 
    }       
}
if (Object[b]!==Object[a]){
    return (Object[b]-Object[a])
}

})

The correct sorting would start with the key values 11 and 13, if flag of key 11 is 0 and flag of key 13 is 1, then sort first [13,11 ...]正确的排序将从键值 11 和 13 开始,如果键 11 的标志为 0 且键 13 的标志为 1,则首先排序[13,11 ...]

The only order that objects give their properties is such that you can't change it for the object you've shown, because the order for properties with names consisting entirely of digits (within the range 0 to 2³²-1) is numeric .对象赋予其属性的唯一顺序是您无法为所显示的对象更改它,因为名称完全由数字(在 0 到 2³²-1 范围内)组成的属性的顺序是numeric So it doesn't matter what you do with that object or another object, the property with the name "11" will always come before the property with the name "42" .因此,无论您对该对象或其他对象做什么,名称为"11"的属性将始终位于名称为"42"的属性之前。

Trying to put objects in a particular order is usually poor practice even when it's possible (which it is with property names that don't consist entirely of digits).尝试按特定顺序放置对象通常是不好的做法,即使可能(这是具有不完全由数字组成的属性名称)。

Instead, use an array of key / value objects, and sort that.相反,使用一组key / value对象,并对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM