尝试对对象中的键进行排序时结果不正确

时间:2018-09-13 20:39:39

标签: javascript node.js

我正在尝试按照降序对对象进行排序,如下所示:

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,但当前输出为greatreadcreditors。可能是什么原因?

2 个答案:

答案 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