Javascript对象排序

Javascript Object Sort

本文关键字:排序 对象 Javascript      更新时间:2024-03-01

我的数据:

books = {};
books[unique_id] = {
   name   : "Zimané Kurdi",
   author : "Leyla Z.",
   date   : "2013.12.12",
   y_no   : 5
}

输出:

$.each(books, function(key, value){
   // shorting "y_no"
});

我该怎么办?(短路"y_no")

谢谢。

假设您询问如何排序,我不建议使用Object.each。相反,给自己设置一个数组,并对其进行排序:

books = [];
books[unique_id] = { // assuming unique_id is numeric, otherwise it won't be an array member
    name   : "Zimané Kurdi",
    author : "Leyla Z.",
    date   : "2013.12.12",
    y_no   : 5
};
// ... presumably adding more objects to books
function compare(a, b) {
    if (a.y_no < b.y_no) {
        return -1;
    } else if (a.y_no > b.y_no) {
        return 1;
    }
    return 0;
}
books.sort(compare);