如何按降序对javascript对象键进行排序?

时间:2019-09-16 15:11:20

标签: javascript jquery sorting

我有一个看起来像这样的JS对象:

data: {
 474481: {
    date: "02/14/2017",
    status_id: "474481"
​​ },
 497070: {
    date: "02/14/2017",
    status_id: "497070"
 },
 797070: {
    date: "02/14/2017",
    status_id: "497070"
 },
 597070: {
    date: "02/14/2017",
    status_id: "497070"
 }
}

如何按键降序对数据对象排序?最终输出应如下所示:

data: {
     797070: {
        date: "02/14/2017",
        status_id: "497070"
     },
     597070: {
        date: "02/14/2017",
        status_id: "497070"
     },
     497070: {
        date: "02/14/2017",
        status_id: "497070"
     },
     474481: {
        date: "02/14/2017",
        status_id: "474481"
    ​​ }
    }

我在项目中使用JQuery 1.9。如果有人对如何对数据进行排序提出建议,请告诉我。

1 个答案:

答案 0 :(得分:0)

如评论中所述,由于对象键不能保持顺序,因此无法对对象进行排序。

您可以在创建 view 之前先对键进行排序。按顺序添加行,将创建一个排序表:

const data = {
     797070: {
        date: "02/14/2017",
        status_id: "497070"
     },
     597070: {
        date: "02/14/2017",
        status_id: "497070"
     },
     497070: {
        date: "02/14/2017",
        status_id: "497070"
     },
     474481: {
        date: "02/14/2017",
        status_id: "474481"
    
    }
};

const table = document.querySelector('table');
Object.keys(data)
.sort((a,b)=>b-a)
.forEach(key => {
  const tr = document.createElement('tr');
  const id = document.createElement('td');
  const date = document.createElement('td');
  const status = document.createElement('td');
  id.innerText = key;
  date.innerText = data[key].date;
  status.innerText = data[key].status_id;
  tr.appendChild(id);
  tr.appendChild(date);
  tr.appendChild(status);
  table.appendChild(tr);
});
<table border="1">
<tr><th>id</th><th>date</th><th>status</th></tr>
</table>