json升序?

格式:

var cases = [{"id":"http://wb.gd.labscare.com/lab/#/public/1011462120167579094","t_code":"B01-R10QY04-001","t_code2":"B01-R10QY04-018","id2":"http://jthg.gd.labscare.com/lab/#/public/1011463417778803040"},{"id":"http://wb.gd.labscare.com/lab/#/public/1011467465864884014","t_code":"B01-R10QY04-005","t_code2":"","id2":""}]

var objData = []

function t_tamiStorage() {
    return {
        id: "",
        t_code: "",
        t_code2: "",
        id2: ""
    }
}

代码

    //最终结果结构体
var idx = 0;
for (var i = 0; i < cases.length; i++) {
    var item = cases[i]
    if(i%2===0){
        var showdata = t_tamiStorage();
        objData.push(showdata);
        showdata.t_code = item['1066989928805654067'];
        showdata.id = getUrl + item.id;
        idx++;
    }else{
        objData[idx-1]['t_code2'] = item['1066989928805654067'];
        objData[idx-1]['id2'] =  getUrl + item.id;
    }

}
objData.sort((a, b) => {
    // 比较t_code
    const tCodeComparison = a.t_code.localeCompare(b.t_code);
    if (tCodeComparison !== 0) return tCodeComparison;
    return a.t_code2.localeCompare(b.t_code2);
  });

console.log(objData)

打印
1691562149613.png

t_code,t_code2是标识符,

请问大佬们这个要排序(升序)呢

阅读 2.3k
2 个回答

还是一样的直接用 Array.sort() 这个API做排序就行了。

var arr = [
  {"t_code": "B01-R10QY04-001", "t_code2": "B01-R10QY04-018" },
  {"t_code": "B01-R10QY04-005", "t_code2": "" },
  {"t_code": "B01-R10QY09-004", "t_code2": "" },
  {"t_code": "B01-R10QY04-002", "t_code2": "" },
  {"t_code": "B01-R10QY04-001", "t_code2": "B01-R10QY04-001" },
  {"t_code": "B01-R10QY04-003", "t_code2": "" },
  {"t_code": "B01-R10QY01-008", "t_code2": "" },
]
// 按照 t_code 排序,如果 t_code 相同,则按照 t_code2 排序
const sortData = arr.sort((a, b) => {
  if (a.t_code === b.t_code) {
    return a.t_code2 > b.t_code2 ? 1 : -1
  }
  return a.t_code > b.t_code ? 1 : -1
})
var arr = [
  {"id":"http://wb.gd.labscare.com/lab/#/public/1011462120167579094","t_code":"B01-R10QY04-001","t_code2":"B01-R10QY04-018","id2":"http://jthg.gd.labscare.com/lab/#/public/1011463417778803040"},
  {"id":"http://wb.gd.labscare.com/lab/#/public/1011467465864884014","t_code":"B01-R10QY04-005","t_code2":"","id2":""}
];

arr.sort((a, b) => {
  // 比较t_code
  const tCodeComparison = a.t_code.localeCompare(b.t_code);
  if (tCodeComparison !== 0) return tCodeComparison;

  return a.t_code2.localeCompare(b.t_code2);
});

console.log(arr);

企业微信截图_16915626047736.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题