首页 > 解决方案 > 按属性值对对象的对象进行排序(通过元组传递)

问题描述

我有这个对象:

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

所以我可以使用toPairsLodash 来创建元组数组,但是如何按total值对它们进行排序呢?

标签: javascript

解决方案


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


推荐阅读