字典在python中排序,但在js中不排序

时间:2018-12-23 11:24:25

标签: javascript python reactjs dictionary

我有一个使用reactjs的网站,后端使用python编写。现在,我有一张照片列表,我想按一个称为“得分”的键对它进行排序。

在python中,我这样做(请告诉我以这种方式进行查询是否安全,我在Flask中使用MySQLdb):

sql = "SELECT id, image_url, score, width, height FROM images ORDER BY score DESC LIMIT 10 OFFSET %s"
        conn.cursor.execute(sql, (offset,))
        images = conn.cursor.fetchall()
        dictImages = {}
        for image in images:
            dictImages[image[0]] = {"url": image[1], "score": image[2], "width": image[3], "height": image[4]}

我的dictImages是:

98: {'url': '62eb97f4496e9bd19755426bde78528f760f1e231545594871.jpg', 'score': 1459, 'width': 720, 'height': 1080}, 
100: {'url': '5a3a28f6f174d5995e6b6d6882e7c055c324f0081545595509.jpg', 'score': 1400, 'width': 1080, 'height': 1080}, 
97: {'url': '2516629bb990e9e8e6a4ccdaeae4048aa83119ee1545550157.JPG', 'score': 1390, 'width': 720, 'height': 899}, 
96: {'url': '6d3236ec3c88039ca534b81acad564e847ecb0621545549723.jpg', 'score': 1381, 'width': 640, 'height': 640}, 
99: {'url': '7a09101b84cd5618bfcdfa8423c16232788bf9691545595051.png', 'score': 1370, 'width': 1080, 'height': 940}

如您所见,它是按分数排序的,但js对象却不是:

  "96": {
    "height": 640, 
    "score": 1381, 
    "url": "6d3236ec3c88039ca534b81acad564e847ecb0621545549723.jpg", 
    "width": 640
  }, 
  "97": {
    "height": 899, 
    "score": 1390, 
    "url": "2516629bb990e9e8e6a4ccdaeae4048aa83119ee1545550157.JPG", 
    "width": 720
  }, 
  "98": {
    "height": 1080, 
    "score": 1459, 
    "url": "62eb97f4496e9bd19755426bde78528f760f1e231545594871.jpg", 
    "width": 720
  }, 
  "99": {
    "height": 940, 
    "score": 1370, 
    "url": "7a09101b84cd5618bfcdfa8423c16232788bf9691545595051.png", 
    "width": 1080
  }, 
  "100": {
    "height": 1080, 
    "score": 1400, 
    "url": "5a3a28f6f174d5995e6b6d6882e7c055c324f0081545595509.jpg", 
    "width": 1080
  }

按键排序。如何避免这个问题?我如何有效订购? (现在,我只有几个键,但应该有更多键。)

谢谢您的任何建议!

1 个答案:

答案 0 :(得分:0)

创建arr时,您使用的是常规对象({}),该对象不会按照元素插入的顺序保留它们。相反,您可以使用一个Map对象来做到这一点:

var arr = new Map();

for(var i=0; ....)
    arr.set(i, VALUE);