简体   繁体   English

如何按数字键值对对象进行排序

[英]How to sort object by numeric key value

I have an object that looks like this:我有一个看起来像这样的对象:

a = {10: 961, 11: 1418, 12: 1526, 13: 1652, 14: 1482, 15: 1581, 16: 1594, 17: 1201, 18: 816, 19: 994, 20: 455, 21: 910, 22: 1181, 23: 713, 00: 296, 01: 144, 02: 100, 03: 56, 04: 22}

How can I rearrange the order of the entries so it looks like如何重新排列条目的顺序,使其看起来像

b = {00: 296, 01: 144, 02: 100, 03: 56, 04: 22, ...}

Not sure if this is relevant but I derive this object from a larger JSON object and need to sort it in order to display the data on a chart.不确定这是否相关,但我从更大的 JSON 对象派生此对象,并且需要对其进行排序以在图表上显示数据。

Properties to objects are ordered by integer values first and then by the string keys in order of their addition to the object.对象的属性首先按整数值排序,然后按字符串键按它们添加到对象的顺序排序。 Therefore it IS possible to order the properties by creating a new object from your object.因此,可以通过从您的对象创建一个新对象来对属性进行排序。

a = {10: 961, 11: 1418, 12: 1526, 13: 1652, 14: 1482, 15: 1581, 16: 1594, 17: 1201, 18: 816, 19: 994, 20: 455, 21: 910, 22: 1181, 23: 713, 00: 296, 01: 144, 02: 100, 03: 56, 04: 22};

b = {};
Object.keys(a).sort((a,b) => { return parseInt(a) - parseInt(b);}).forEach((x) => {
b[x] = a[x];});
console.log(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM