对JSON数组进行排序并使用$ .each进行回显

时间:2015-07-03 16:37:43

标签: javascript jquery arrays json

所以目前我有一个看起来像这样的JSON数组

"series": [{
        "book": 1,
        "chapter": 1,
        "title": "Title of this chapter",
    },
    {
        "book": 1,
        "chapter": 2,
        "title": "Title of this chapter",
    },
    {
        "book": 1,
        "chapter": 3,
        "title": "Title of this chapter",
    },
    {
        "book": 2,
        "chapter": 1,
        "title": "Title of this chapter",
    },
    {
        "book": 2,
        "chapter": 2,
        "title": "Title of this chapter",
    }]

我需要用jQuery来回应它,所以我可以为每本书做$ .each,并为每一章做$ .each。

目前我已经完成$ .each,然后将结果附加到页面,然后尝试使用外部jQuery插件对其进行排序,但无济于事。

2 个答案:

答案 0 :(得分:1)

使用该JSON,您需要创建一个中间数组的书籍,以便将给定书籍的所有章节组合在一起。然后,在那个中间结构(现在是book个对象的数组)上,你可以遍历它们并吐出章节。

var json = //your JSON object
var books = {};
$.each(json.series,function(i,book) {
   if(!books.hasOwnProperty(book.book)) {
      books[book.book] = [];
   }
      books[book.book].push(book);
});

//now that you have each book in it's own array
$.each(books,function(i,book) {
   $.each(book,function(i,chapter) {
       console.log('Book ' + chapter.book + ', Chapter ' + chapter.chapter + ':' + chapter.title);
   });
});

如果您的书籍/章节不合规,那么您需要先对它们进行排序。从原始JSON对象开始:

json.series.sort(function(a,b) {
    return a.book-b.book || a.chapter-b.chapter;
});

答案 1 :(得分:-1)

试试这个:

    var json = '{"series":[{"book":"1","chapter":"1","title": "Title of this chapter"},{"book":"2","chapter":"2","title": "Title of this chapter"}]}';

    var serieslist = $.parseJSON(json);
    var series_books = {};
    $.each(serieslist.series, function(index,book){
       series_books.push(book);
    });

   $.each(series_books,function(i,book) {
      $.each(book,function(i,chapter) {
        //do what you need to here ...
      });
   })

希望这有帮助,使用$ .parseJSON将JSON字符串解析为可用对象,然后根据需要操作它们。