Sorting a JavaScript object by property name

后端 未结 6 1190
遥遥无期
遥遥无期 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:54

    This should be used with caution as your code shouldn't rely on Object properties order. If it's just a matter of presentation (or just for the fun !), you can sort properties deeply like this :

    function sortObject(src) {
      var out;
      if (typeof src === 'object' && Object.keys(src).length > 0) {
        out = {};
        Object.keys(src).sort().forEach(function (key) {
          out[key] = sortObject(src[key]);
        });
        return out;
      }
      return src;
    }
    

提交回复
热议问题