如何在JS中迭代嵌套对象

时间:2012-06-27 16:18:28

标签: javascript jquery object nested

好的,我很难过这个。 我需要迭代这些,所以我可以按类别列出类似

的列表
  

商业书籍

     

第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."
       }
    ],
};

4 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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);
        }
    });

答案 2 :(得分:1)

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

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

答案 3 :(得分: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