gpt4 book ai didi

javascript - 基于嵌套对象值的对象排序

转载 作者:行者123 更新时间:2023-12-03 03:11:46 24 4
gpt4 key购买 nike

我有一个对象,我想根据它所拥有的投票对其进行排序,然后映射到新的/已排序的对象。

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)

最终,我希望这个新对象仍然保留 comment-### 键,并根据其拥有的票数进行过滤。例如 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.valuesObject.entries 走在正确的轨道上,但我真的对此很着迷。

任何帮助将不胜感激,谢谢!

https://codepen.io/MathiasaurusRex/pen/RLzYVV

最佳答案

您可以使用 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);

关于javascript - 基于嵌套对象值的对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com