narfie
narfie

Reputation: 493

Reverse JSON object

Hi I have a JSON object ("/satisfaction_ratings.json"):

{
"satisfaction_ratings": [{
    "id": 217414761,
    "updated_at": "2015-02-26T07:15:32Z",
    "comment": "You are awesome!"
}, {
    "id": 217419001,
    "updated_at": "2015-02-28T17:45:39Z",
    "comment": "You are great!"
}, {
    "id": 220481332,
    "updated_at": "2015-03-01T11:19:56Z",
    "comment": "You are brilliant!"
}, {
    "id": 218225121,
    "updated_at": "2015-03-02T05:36:08Z",
    "comment": "You are fantastic!"
}, {
    "id": 228307861,
    "updated_at": "2015-03-25T18:39:47Z",
    "comment": "You are incredible!"
}],
"next_page": null,
"previous_page": null,
"count": 5
}

...some html:

<div id="feedback"></div>

...and some jQuery:

<script>
$.getJSON( "/satisfaction_ratings.json", function( data ) {
  var items = [];
  $.each(data.satisfaction_ratings, function() {
        // console.log(this.comment);   
        items.push("<li>" + this.comment + "</li>");
  });

$( "<ul/>", {
    "class": "comments_list",
    html: items.join( "" )
  }).

appendTo( "#feedback" );

});
</script>

In the JSON object, my comments are ordered by date ascending. I would like to display them on my page in reverse order (so that the most recent is at the top).

I've tried the following:

$.reverse().each(data.satisfaction_ratings, function() {...});
Object.keys(data.satisfaction_ratings).sort().reverse().forEach(function(){...});

and all sorts of other ways. I'm just not sure I understand what to do in order to iterate through my JSON object in reverse order.

Upvotes: 0

Views: 4258

Answers (1)

Jamiec
Jamiec

Reputation: 136124

Try reversing the array before using each

$.each(data.satisfaction_ratings.reverse(), function() {
    // console.log(this.comment);   
    items.push("<li>" + this.comment + "</li>");
});

var json = {
"satisfaction_ratings": [{
    "id": 217414761,
    "updated_at": "2015-02-26T07:15:32Z",
    "comment": "You are awesome!"
}, {
    "id": 217419001,
    "updated_at": "2015-02-28T17:45:39Z",
    "comment": "You are great!"
}, {
    "id": 220481332,
    "updated_at": "2015-03-01T11:19:56Z",
    "comment": "You are brilliant!"
}, {
    "id": 218225121,
    "updated_at": "2015-03-02T05:36:08Z",
    "comment": "You are fantastic!"
}, {
    "id": 228307861,
    "updated_at": "2015-03-25T18:39:47Z",
    "comment": "You are incredible!"
}],
"next_page": null,
"previous_page": null,
"count": 5
};

$.each(json.satisfaction_ratings.reverse(),function(){
    $('ul').append('<li>' + this.comment + '</li>');  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>

Upvotes: 7

Related Questions