目前我有一个如下所示的 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 插件对其进行排序,但无济于事。
最佳答案
使用该 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;
});
关于javascript - 对 JSON 数组进行排序并使用 $.each 进行回显,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211159/