search

Home  >  Q&A  >  body text

javascript - sorting objects

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

天蓬老师天蓬老师2764 days ago475

reply all(5)I'll reply

  • 巴扎黑

    巴扎黑2017-05-19 10:12:41

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:12:41

      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.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:12:41

    var obj = { /* ..略.. */ }
    
    var res = Object.keys(obj).map(e => parseInt(e)).sort().map(e => obj[e]);

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:12:41

    JS objects are unordered.
    Also:
    {

    "11": "aaa"

    }
    The 11 inside is a string.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:12:41

    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]);
        }

    reply
    0
  • Cancelreply