【发布时间】:2018-03-18 18:44:49
【问题描述】:
我有一个对象
const posts = {
"BAhvZrRwcfu":{
"text":"Totally need to try this.",
"user": "heavymetaladam",
vote: 2
},
"BAcyDyQwcXX":{
"text":"Wes. WE should have lunch.",
"user": "jdaveknox",
vote : 3
}
};
有没有一种方法可以根据投票进行排序。如果我将其设为对象数组似乎更容易
【问题讨论】:
-
是的,有一些可以尝试的方法。您能否在问题中包含您尝试解决查询的代码?见stackoverflow.com/help/mcve
-
不仅更简单,而且可以排序。
-
@linux 请参阅下面的答案。你用了钥匙。你想要价值观。
-
var keys = Object.keys(state.posts); keys.sort((a, b) => { if (a.voteScore < b.voteScore) { return -1; } if (a.voteScore > b.voteScore) { return 1; } // a.voteScore must be equal to b.voteScore return 0; }).reduce((a, v) => { return state.posts[v] }, {}) -
It seems easier if i make it an array of object- 是的,你在这一点上是对的,因为对象不是“可排序的”,数组是
标签: javascript json sorting