Sorting JSON by values

前端 未结 6 1089
北荒
北荒 2020-11-22 12:16

I have a very simple JSON object like the following:

{
   \"people\":[
      {
         \"f_name\":\"john\",
         \"l_name\":\"doe\",
         \"sequence         


        
6条回答
  •  余生分开走
    2020-11-22 12:36

    jQuery isn't particularly helpful for sorting, but here's an elegant and efficient solution. Just write a plain JS function that takes the property name and the order (ascending or descending) and calls the native sort() method with a simple comparison function:

    var people = [
        {
            "f_name": "john",
            "l_name": "doe",
            "sequence": "0",
            "title" : "president",
            "url" : "google.com",
            "color" : "333333",
        }
        // etc
    ];
    
    function sortResults(prop, asc) {
        people.sort(function(a, b) {
            if (asc) {
                return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
            } else {
                return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            }
        });
        renderResults();
    }
    

    Then:

    sortResults('l_name', true);
    

    Play with a working example here.

提交回复
热议问题