javascript - 按属性值对对象的对象进行排序(通过元组传递)
问题描述
我有这个对象:
const data = {
FR: {total: 875, min: 4, cutValue: 56},
DE: {total: 478, min: 50, cutValue: 5},
UK: {total: 1505, min: 0, cutValue: 0},
PO: {total: 2995, min: 0, cutValue: 4},
IT: {total: 1840, min: 10, cutValue: 3},
ES: {total: 629, min: 30, cutValue: 33},
}
total
我想将它转换为按值排序的元组数组。所以结果应该是:
[
['PO', {total: 2995, min: 0, cutValue: 4}],
['IT', {total: 1840, min: 10, cutValue: 3}],
['UK', {total: 1505, min: 0, cutValue: 0}],
['FR', {total: 875, min: 4, cutValue: 56}],
['ES', {total: 629, min: 30, cutValue: 33}],
['DE', {total: 478, min: 50, cutValue: 5}],
]
因为价值PO
最高total
。
所以我可以使用toPairs
Lodash 来创建元组数组,但是如何按total
值对它们进行排序呢?
解决方案
您可以使用.sortBy
:
const data = {
FR: {total: 875, min: 4, cutValue: 56},
DE: {total: 478, min: 50, cutValue: 5},
UK: {total: 1505, min: 0, cutValue: 0},
PO: {total: 2995, min: 0, cutValue: 4},
IT: {total: 1840, min: 10, cutValue: 3},
ES: {total: 629, min: 30, cutValue: 33},
};
const sorted = _.sortBy(_.toPairs(data), ([, { total }]) => -total);
console.log(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
推荐阅读
- python - 可以为多个列设置类别和类型吗?
- python - 使用 Python 和 winreg 在 Windows 10 上设置代理
- google-chrome - Chrome 扩展程序:从弹出窗口访问数据
- java - 使用 Hashmap 检测列表中的重复项和重复项计数
- python - 如何使用 Telethon 运行多个会话?
- python - 边界附近有更多点的非均匀间隔的 np.array
- java - 如何检查远程存储库中是否存在依赖项?
- python - 为什么我的第二个数据库列填充了“无”?
- sqlite - 在 Delphi 10.3 Community Edition 中使用 SQLite 的最佳和简单方法是什么?
- android - iOS 模拟器或物理设备未收到 FCM 数据消息