How to sort a Javascript object, or convert it to an array?

前端 未结 7 584
囚心锁ツ
囚心锁ツ 2020-12-13 04:13

I have some JSON data that I get from a server. In my JavaScript, I want to do some sorting on it. I think the sort() function will do what I want.

However, it seems

7条回答
  •  甜味超标
    2020-12-13 04:40

    Most of these answers over-complicate the issue or use JQuery or Underscore whereas the OP never asked for those.

    You can convert an object to an array like this:

    myArray= Object.keys(data).map(function(key) { return data[key] });
    

    And sort the result like this:

    myArray.sort(function(x, y) {return x.level - y.level});
    

    If you need the id/index, then you need to do a bit more:

    Object.keys(data).map(function(key) { 
      var obj = data[key];
      obj.index = key;
      return obj 
    });
    

提交回复
热议问题