【问题标题】:How to sort a nested object based on key name如何根据键名对嵌套对象进行排序
【发布时间】:2022-01-01 07:45:27
【问题描述】:

我有一个看起来像这样的嵌套对象。我想根据 Districtnames 的字母顺序按升序和降序对其进行排序。

var data = 
{"DistrictC":{"population":105597},
"DistrictB":{"population":36842},
"DistrictA":{"population":238142}}

按升序的预期输出如下所示。我还需要按降序排序。

{"DistrictA":{"population":238142},
"DistrictB":{"population":36842},
"DistrictC":{"population":105597}}

【问题讨论】:

  • 对象并不意味着有秩序。 JS 引擎会保持秩序,但不能保证。

标签: javascript reactjs json object javascript-objects


【解决方案1】:

您可以使用Object.entries 获取键/值对数组,然后使用localeCompare 对键进行排序:

const data = {
  "DistrictC":{"population":105597},
  "DistrictB":{"population":36842},
  "DistrictA":{"population":238142}
}

const sorted = Object.entries(data)
  .sort(([keyA], [keyB]) => keyA.localeCompare(keyB));

console.log(sorted);

您可以使用map 将键/值数组折叠成对象,从而使该结果更易于使用:

// same as before
const data = {
  "DistrictC":{"population":105597},
  "DistrictB":{"population":36842},
  "DistrictA":{"population":238142}
}

// same as before
const sorted = Object.entries(data)
  .sort(([keyA], [keyB]) => keyA.localeCompare(keyB));

const collapsed = sorted.map(([district, value]) => ({ district, ...value }));

// ascending
console.log(collapsed);

// descending
console.log(collapsed.reverse());

【讨论】:

  • 如何降序排序?
  • 不是按人口排序的......
  • 不应该。阅读问题(ascending and descending order based on the alphabetical order of Districtnames):P
  • 按地区名称字母倒序排列,不按人口。
  • 要颠倒顺序,您可以在 localeCompare 表达式中交换 keyA 和 keyB:keyB.localeCompare(keyA),或者在排序后附加 .reverse()
猜你喜欢
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 2019-06-25
  • 2021-07-20
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多