Sorting a JavaScript object by property name

后端 未结 6 1185
遥遥无期
遥遥无期 2020-11-22 16:24

I\'ve been looking for a while and want a way to sort a Javascript object like this:

{
    method: \'artist.getInfo\',
    artist: \'Green Day\',
    format:         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 16:52

    this function takes an object and returns a sorted array of arrays of the form [key,value]

    function (o) {
       var a = [],i;
       for(i in o){ 
         if(o.hasOwnProperty(i)){
             a.push([i,o[i]]);
         }
       }
       a.sort(function(a,b){ return a[0]>b[0]?1:-1; })
       return a;
    }
    

    The object data structure does not have a well defined order. In mathematical terms, the collection of keys in an object are an Unordered Set, and should be treated as such. If you want to define order, you SHOULD use an array, because an array having an order is an assumption you can rely on. An object having some kind of order is something that is left to the whims of the implementation.

提交回复
热议问题