5

好吧,我被这个难住了。我需要遍历这些,所以我可以按类别列出这样的东西

商业书籍

第一册

书 2

书 3

烹饪书籍

ETC..

但无法弄清楚如何遍历嵌套对象。有或没有 jquery 都很好

window.books = {
    "Business Books": [
       {
           Title: "Finance 101",
           Description: "Info for Finance 101 book goes here."
       },
       {
           Title: "Economics 123",
           Description: "Info for Economics 123 book goes here."
       },
       {
           Title: "Statistics for Beginners",
           Description: "Learn about Statistics."
       }
    ],
    "Cooking Books": [
       {
           Title: "Lowfat Treats",
           Description: "Eat a lowfat Diet"
       },
       {
           Title: "Chocolate Lovers",
           Description: "Eat a lot of chocolate"
       },
       {
           Title: "Book of Brownies",
           Description: "Stuff about Brownies"
       }
    ],
    "IT Books": [
       {
           Title: "Windows XP",
           Description: "Please go away"
       },
       {
           Title: "Linux",
           Description: "A how to guide."
       },
       {
           Title: "Unix",
           Description: "All about Unix."
       },
       {
           Title: "Mac",
           Description: "Costs too much."
       }
    ],
};
4

4 回答 4

10

好主意是先学习如何在没有 jQuery 的情况下做到这一点。

for(var category in window.books) {
  if(window.books.hasOwnProperty(category)) {
    console.log(category); // will log "Business Books" etc.
    for (var i = 0, j = window.books[category].length; i < j; i++) {
      console.log("Title: %s, Description: %s", window.books[category][i].Title, window.books[category][i].Description);
    }
  }
}

然后你可以使用$.each().

于 2012-06-27T16:27:06.697 回答
2
$.each(window.books,function(k,v){   // k ==== key, v === value
        // Prints category
        console.log(k); 

        //Loops through category
        for(i=0,len=v.length;i<len;i++){
            console.log(v[i].Title);
            console.log(v[i].Description);
        }
    });
于 2012-06-27T16:34:46.800 回答
1
jQuery.each(window.books, function(category, items) {
    alert(category);

    jQuery.each(items, function(idx, book) {
        alert(category + ': ' + book.Title)
    });
});
于 2012-06-27T16:25:32.877 回答
0

使用 .each() 循环非常简单:

$.each(window.books, function(category, books) {                                    
    $("#books").append("<p>" + category + "</p><ul>");                              
    $.each(books, function(i, book) {                                               
        $("#books").append("<li>" + book.Title + ": " + book.Description + "</li>");
    });                                                                             
    $("#books").append("</ul>");                                                    
});                      

这是我的jsFiddle

于 2012-06-27T16:32:51.107 回答