我正在尝试按照降序对对象进行排序,如下所示:
const searchResults = {
"great": {
"length": 5,
"occurance": 301487430,
"rank": -1
},
"read": {
"length": 4,
"occurance": 322331766,
"rank": 10
},
"creditors": {
"length": 9,
"occurance": 3211591,
"rank": -1
}
}
// The way I am trying to sort is as follows:
let keys = Object.keys(searchResults);
let sortByEM = keys.sort((a, b) => Number(searchResults[b.rank]) - Number(searchResults[a.rank]));
console.log(sortByEM);
输出应首先为read
,然后为great
/ creditors
,但当前输出为great
,read
和creditors
。可能是什么原因?
答案 0 :(得分:3)
您试图以错误的方式访问属性。代替
searchResults[b.rank]
您正在寻找
searchResults[b].rank
您的代码searchResults[b.rank]
试图访问表达式b.rank
返回的属性名称,该属性名称当然是未定义的(因为b
只是string
)。 searchResults.undefined
ofc也是未定义的,因此您的排序函数尝试从undefined
中减去undefined
-本质上这意味着您的排序函数不执行任何操作。
const searchResults = {
"great": {
"length": 5,
"occurance": 301487430,
"rank": -1
},
"read": {
"length": 4,
"occurance": 322331766,
"rank": 10
},
"creditors": {
"length": 9,
"occurance": 3211591,
"rank": -1
}
}
let keys = Object.keys(searchResults);
let sortByEM = keys.sort((a, b) => (searchResults[b].rank - searchResults[a].rank));
console.log(sortByEM);
答案 1 :(得分:2)
您错误地访问了对象。
应改为searchResults[b.rank]
,而不是searchResults[b].rank
。