简体   繁体   English

对对象中的数字键进行排序

[英]Sort numeric keys in object

I have an object with keys and values are integer: 我有一个带有键的对象,值是整数:

{
  10: 3,
  20: 3,
  30: 3,
  60: 1
}

I want to sort this object as 我想将此对象排序为

{
  60: 1,
  30: 3,
  20: 3,
  10: 3
}

Are you have any solutions to solve my problems? 您有解决我问题的解决方案吗?

Sorry for my bad English! 对不起,我的英语不好!

4.3.3 Object An object is a member of the type Object. 4.3.3对象对象是对象类型的成员。 It is an unordered collection of properties each of which contains a primitive value, object, or function. 它是属性的无序集合 ,每个属性都包含原始值,对象或函数。 A function stored in a property of an object is called a method. 存储在对象属性中的函数称为方法。

see Standard ECMA-262 参见标准ECMA-262

I´ve prepared a little solution for you. 我为您准备了一些解决方案。 Converting it first to an array, and then sorting by the property you need. 首先将其转换为数组,然后根据所需属性进行排序。

Also showing in the print the difference between objects {} and arrays [] . 还显示了对象{}与数组[]之间的区别。 Check the fiddle, there you have a sorted array with the values from you object. 检查小提琴,您有一个带有对象值的排序数组。

 var obj = { 10: 3, 20: 3, 30: 3, 60: 1 }; var keys = Object.keys(obj); var arr = []; for (i = 0; i < keys.length; i++) { arr.push({ val: obj[keys[i]], key: keys[i] }); } var ordered = false; while (!ordered) { var i = 0; ordered = true; for (i = 0; i < arr.length - 1; i++) { if (arr[i].val > arr[i + 1].val) { var pass = arr[i + 1].val; var passkey = arr[i + 1].key; arr[i + 1].val = arr[i].val; arr[i + 1].key = arr[i].key; arr[i].val = pass; arr[i].key = passkey; ordered = false; } } } var newObj = {}; for (i = 0; i < arr.length; i++) { newObj[arr[i].key] = arr[i].val console.log("val:" + arr[i].val + ",key:" + arr[i].key); } document.write("<p>THE ARRAY:" + JSON.stringify(arr) + "</p>"); document.write("<p>THE OBJECT:" + JSON.stringify(newObj) + "</p>"); 

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

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