-1

I have a json object coming from an external JSON file (I cannot change this):

{
    "lcContact": {
        "Alternate1": {
            "last_name": "Williams",
            "first_name": "Robert",
            "rank": 5
        },
        "Alternate2": {
            "last_name": "Crowley",
            "first_name": "Joseph",
            "rank": 9
        },
        "Primary": {
            "last_name": "Garbolino",
            "first_name": "Robert",
            "rank": 2
        }
    }

}

Then, I am using jQuery to read this:

$.getJSON('file.json', function(json) {
            object = json;
            var this_parent = Object.keys(json)[0];
            $.each(json[this_parent], function(this_parent) {

            html += '<tr><td class="rank">' + this.rank + '</td><td>' + this.first_name + ' ' + this.last_name +'</td><td class="rank">' + this.rank + '</td></tr>';


            });
            $('table tbody.active').html(html);
    });

My problem is that the ranks are coming through in random order (5,9,2). I need to output the JSON data in order by rank.

Can someone please help me to output the data IN ORDER based on the person's rank?

Please let me know if you need more information. Thanks in advance!

3 Answers3

1
$.getJSON('file.json', function(json) {
    var temp = []; //create array
    for(var i in json.lcContact) temp.push(json.lcContact[i]);  //fill array
    var sorted = temp.sort(function(a,b){ return a.rank - b.rank; });  //sort array 
    console.log(sorted);  //display array
    //loop through....
});
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

I would insert an intermediate step to convert it into an Array and sort it using a custom sort function. Here's basically what I would do in that intermediate step:

function sortObj(obj) {
  var array = [];
  for (var i in obj) {
    if obj.hasOwnProperty(i) {
      array.push({key: i, value: obj[i]});
    }
  }
  array.sort(function (a, b) {
    return a.value["rank"] - b.value["rank"];
  });
  return array;
}

The reason I'm saving the keys is because it may be needed later. (I am well aware of YAGNI, but that would limit this code's reuse).

Claudia
  • 1,197
  • 15
  • 30
0

You can convert it to an array, sort it, and then create the appropriate elements, like this

$('table tbody.active').html(function() {
    return $.map(json[Object.keys(json).shift()], function(par) {
        return par;
    }).sort(function(a, b) {
        return a.rank - b.rank;
    }).map(function(obj) {
        return $('<tr />').append(
            $('<td />', {'class': 'rank', text : obj.rank}),
            $('<td />', {text: obj.first_name + ' ' + obj.last_name}),
            $('<td />', {'class': 'rank', text : obj.rank})
        )
    });
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388