How do I sort a JSON object by a nested value?

前端 未结 2 1358
北恋
北恋 2021-01-02 08:28

I have an ajax call that returns a JSON object that is pretty complex and I\'m having a hard time sorting it.

My call:

$.post(\'/reports-ajax\',argu         


        
2条回答
  •  -上瘾入骨i
    2021-01-02 09:31

    What you have there isn't an array and has no order, so you'll have to transform it into an array so you can give it order.

    Vaguely:

    var array = [];
    $.each(data, function(key, value) {
        array.push(value);
    });
    array.sort(function(a, b) {
        return a.net_total - b.net_total;
    });
    

    Live Example | Source

    As GolezTroi points out in the comments, normally the above would lose the key that each entry is stored under in data and so you'd add it back in the first $.each loop above, but in this case the entries already have the key on them (as number), so there's no need.

    Or you can replace the first $.each with $.map:

    var array = $.map(data, function(entry) {
        return entry;
    });
    // ...and then sort etc.
    

    ...whichever you prefer.

提交回复
热议问题