Jquery按其键值排序对象

时间:2016-10-05 13:05:28

标签: javascript jquery sorting

我有以下对象:

Object {by: "abritishguy", descendants: 38, id: 12617659, kids: Array[8], score: 133…}
Object {by: "mcgwiz", descendants: 4, id: 12641662, kids: Array[1], score: 8…}
Object {by: "dnetesn", descendants: 19, id: 12617263, kids: Array[5], score: 73…}
Object {by: "samber", descendants: 12, id: 12631162, kids: Array[6], score: 127…}
Object {by: "seanseanme", descendants: 0, id: 12632377, score: 16, time: 1475539307…}
Object {by: "wolframio", descendants: 3, id: 12631876, kids: Array[3], score: 25…}
Object {by: "paloaltokid", descendants: 22, id: 12620209, kids: Array[19], score: 11…}
Object {by: "vfulco", descendants: 1, id: 12620860, kids: Array[2], score: 7…}
Object {by: "forgingahead", descendants: 0, id: 12641351, score: 8, time: 1475638119…}
Object {by: "aylmao", descendants: 0, id: 12630489, score: 4, time: 1475522605…}

我需要通过"得分"

对上述对象进行排序

到目前为止,我试过这个:

$.getJSON('data.json', function (idata) {
    itemDataArray.push(idata);

});


$(itemDataArray).sort( function ( a, b ) {
    var attr = {}; // your comparison attribute here
    attr.a = parseInt( a.data( 'score' ) || 0 );
    attr.b = parseInt( b.data( 'score' ) || 0 );
    return attr.a < attr.b ? -1 : attr.a > attr.b ? 1 : 0;
});

它不起作用,请帮助

1 个答案:

答案 0 :(得分:1)

您可以直接使用Array#sort

在这种情况下,由于-运算符,可能的字符串值被隐式转换为数字。

升序:

itemDataArray.sort(function (a, b) {
    return a.score - b.score;
});

降序:

itemDataArray.sort(function (a, b) {
    return b.score - a.score;
});