我有一个对象,我想根据它的投票进行排序,然后映射新的/已排序的对象。
const data = {
"comment-1508872637211" : {
"description" : "Blah",
"votes" : 1
},
"comment-1508872675949" : {
"description" : "Question",
"votes" : 11
},
"comment-1508898578089" : {
"description" : "whatever\n",
"votes" : 5
},
"comment-1508898637092" : {
"description" : "new",
"votes" : 15
},
"comment-1508900306998" : {
"description" : "baj",
"votes" : 0
}
}
console.log(data);
const sortedOnVotes = Object.entries(data);
console.log(sortedOnVotes);
// This is the part I'm getting hung up on
const newDataObject = sortedOnVotes.map(([key, value]) => value).sort();
console.log(newDataObject)
最终,我希望这个新对象仍然保留评论 - ###密钥,并根据其拥有的投票数量进行过滤。例如,newDataObject应返回如下内容:
const newDataObject = {
"comment-1508900306998" : {
"description" : "baj",
"votes" : 0
},
"comment-1508872637211" : {
"description" : "Blah",
"votes" : 1
},
"comment-1508898578089" : {
"description" : "whatever\n",
"votes" : 5
},
"comment-1508872675949" : {
"description" : "Question",
"votes" : 11
}
"comment-1508898637092" : {
"description" : "new",
"votes" : 15
}
}
我认为我使用Object.values
或Object.entries
走在了正确的轨道上,但我真的很喜欢它。
真的很感激任何帮助,谢谢!
答案 0 :(得分:1)
您可以使用sort()
函数编写逻辑来对数组进行排序,如下所示 -
const data = {
"comment-1508872637211" : {
"description" : "Blah",
"votes" : 1
},
"comment-1508872675949" : {
"description" : "Question",
"votes" : 11
},
"comment-1508898578089" : {
"description" : "whatever\n",
"votes" : 5
},
"comment-1508898637092" : {
"description" : "new",
"votes" : 15
},
"comment-1508900306998" : {
"description" : "baj",
"votes" : 0
}
}
console.log(data);
const sortedOnVotes = Object.entries(data);
console.log(sortedOnVotes);
var result = sortedOnVotes.sort(function(a,b) {
return a[1].votes - b[1].votes;
});
console.log(result);