2012-06-27 115 views
5

好吧,我难住这个。 我需要通过这些迭代,所以我可以按类别的列表所以像如何通过JS中的嵌套对象进行迭代

商业书籍

书1

书2

书3

烹饪图书

等。

但无法弄清楚如何遍历嵌套的对象。 带或不带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." 
     } 
    ], 
}; 
+0

遍历对象的属性。每个对象都有一组值。遍历数组。这需要一个嵌套for循环。看看https://developer.mozilla.org/en/JavaScript/Guide/Statements#Loop_Statements –

回答

1
jQuery.each(window.books, function(category, items) { 
    alert(category); 

    jQuery.each(items, function(idx, book) { 
     alert(category + ': ' + book.Title) 
    }); 
}); 
9

好主意是要学会先做它没有jQuery的。可以使用$.each()

+0

同意。最好的建议! –

0

用。每次循环()是很容易的:

$.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

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); 
     } 
    });