反转JSON对象

时间:2015-03-27 13:25:47

标签: jquery json

您好我有一个JSON对象(" /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
}

...一些HTML:

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

...和一些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>

在JSON对象中,我的注释按日期升序排序。我想以相反的顺序在我的页面上显示它们(以便最新的位于顶部)。

我尝试过以下方法:

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

以及各种其他方式。我只是不确定我是怎么做的,以便以相反的顺序迭代我的JSON对象。

1 个答案:

答案 0 :(得分:5)

在使用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>