通过嵌套属性对字典的键进行排序

时间:2018-01-24 09:56:27

标签: javascript sorting dictionary

我有这种字典:

const recommendations =
 { '014A8C3D-FE99-4DE3-9F9F-F197A3CB270F': 
   { zL: 0.0402632597754549,
     zD: 0,
     mL: 2,
     mD: 0,
     rate: 0.02013162988772745 },
  '036EA860-FDF1-40DA-8915-A2F02241DC7D': 
   { zL: 0.0297356539387,
     zD: 0,
     mL: 1,
     mD: 0,
     rate: 0.0297356539387 },
  '4A49B2C5-62A6-494B-BE77-FBEF5C102579': 
   { zL: 0.052390243902439025,
     zD: 0,
     mL: 1,
     mD: 0,
     rate: 0.052390243902439025 },
  '640674E4-5080-4BFD-983F-330D1C9150D0': 
   { zL: 0.011376894745,
     zD: 0,
     mL: 1,
     mD: 0,
     rate: 0.011376894745 }
 }

每个键都是“推荐标识符”,每个值都是推荐属性的字典。

我想获得一系列推荐ID,按'rate'属性(降序)排序:

//sortedRecommendations
['4A49B2C5-62A6-494B-BE77-FBEF5C102579',
'036EA860-FDF1-40DA-8915-A2F02241DC7D',
'014A8C3D-FE99-4DE3-9F9F-F197A3CB270F',
'640674E4-5080-4BFD-983F-330D1C9150D0']

我想我应该首先将我的字典(不可排序)转换为数组(可排序)。但后来我找不到获得预期结果的方法......

3 个答案:

答案 0 :(得分:4)

您可以通过获取比较属性的增量来按rate属性降序排序。



var recommendations = { '014A8C3D-FE99-4DE3-9F9F-F197A3CB270F': { zL: 0.0402632597754549, zD: 0, mL: 2, mD: 0, rate: 0.02013162988772745 }, '036EA860-FDF1-40DA-8915-A2F02241DC7D': { zL: 0.0297356539387, zD: 0, mL: 1, mD: 0, rate: 0.0297356539387 }, '4A49B2C5-62A6-494B-BE77-FBEF5C102579': { zL: 0.052390243902439025, zD: 0, mL: 1, mD: 0, rate: 0.052390243902439025 }, '640674E4-5080-4BFD-983F-330D1C9150D0': { zL: 0.011376894745, zD: 0, mL: 1, mD: 0, rate: 0.011376894745 } },
    keys = Object
        .keys(recommendations)
        .sort((a, b) => recommendations[b].rate - recommendations[a].rate);

console.log(keys);




答案 1 :(得分:2)

这很有效。

const recommendations =
{ '014A8C3D-FE99-4DE3-9F9F-F197A3CB270F': 
 { zL: 0.0402632597754549,
   zD: 0,
   mL: 2,
   mD: 0,
   rate: 0.02013162988772745 },
'036EA860-FDF1-40DA-8915-A2F02241DC7D': 
 { zL: 0.0297356539387,
   zD: 0,
   mL: 1,
   mD: 0,
   rate: 0.0297356539387 },
'4A49B2C5-62A6-494B-BE77-FBEF5C102579': 
 { zL: 0.052390243902439025,
   zD: 0,
   mL: 1,
   mD: 0,
   rate: 0.052390243902439025 },
'640674E4-5080-4BFD-983F-330D1C9150D0': 
 { zL: 0.011376894745,
   zD: 0,
   mL: 1,
   mD: 0,
   rate: 0.011376894745 }
};
 
var recommendationkeys = Object.keys(recommendations);

recommendationkeys.sort(function(first,second){
    return recommendations[second].rate - recommendations[first].rate;
});

console.log(recommendationkeys);

答案 2 :(得分:1)

使用Object.keys()Array.sort()

Object.keys(recommendations).sort((a, b) => ( recommendations[a].rate < recommendations[b].rate ? -1 : 1)); //asc

Object.keys(recommendations).sort((a, b) => ( recommendations[a].rate < recommendations[b].rate ? 1 : -1)); //desc

编辑:a.rate确实是未定义的。建议并[a] .rate