javascript - sorting objects
天蓬老师
天蓬老师 2017-05-19 10:10:41
0
5
525

As shown in the figure, I want to perform reverse order based on "1", "99", and "23"; it becomes

NvTC

May I ask the master who knows? Thank you

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(5)
巴扎黑

In Object, data is stored in key => value pairs, so there is no order problem

Peter_Zhu
  1 var obj = {
  2     '1':{
  3         val:'red'
  4      },
  5      '99':{
  6         val:'yellow'
  7      },
  8      '37':{
  9         val:'blue'
 10      }
 11 };
 12
 13 function selirizeData(obj){
 14     var keys = Object.keys(obj).sort(function(a,b){
 15         return a-b;
 16     });
 17     var newObj = {};
 18     keys.forEach(function(val){
 19         newObj[val] = obj[val];
 20     });
 21     console.log(keys);
 22     console.log(newObj);
 23 }
 24 selirizeData(obj);

First use Object.keys() to get the key array of the object, then use the array sorting method to sort, then use the array's foreach method to loop through the array, sort the original object's data and write it to the new object.

伊谢尔伦
var obj = { /* ..略.. */ }

var res = Object.keys(obj).map(e => parseInt(e)).sort().map(e => obj[e]);

淡淡烟草味

JS objects are unordered.
Also:
{

"11": "aaa"

}
The 11 inside is a string.

淡淡烟草味

Thoughts:forin所有的keyArray,排序Array.sort(),遍历Array,按顺序取值obj[key]

    var keys = [];
    for (var i in obj) {
        keys.push(i);
    }
    keys.sort();
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        console.log(obj[key]);
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template